Pyspark 不同列上的不同聚合操作
我试图将不同的聚合函数应用于pyspark数据帧中的不同列。根据有关stackoverflow的一些建议,我尝试了以下方法:Pyspark 不同列上的不同聚合操作,pyspark,Pyspark,我试图将不同的聚合函数应用于pyspark数据帧中的不同列。根据有关stackoverflow的一些建议,我尝试了以下方法: the_columns = ["product1","product2"] the_columns2 = ["customer1","customer2"] exprs = [mean(col(d)) for d in the_columns1, count(col(c)) for c in the_columns2] 接 df.groupby(*group).a
the_columns = ["product1","product2"]
the_columns2 = ["customer1","customer2"]
exprs = [mean(col(d)) for d in the_columns1, count(col(c)) for c in the_columns2]
接
df.groupby(*group).agg(*exprs)
其中,“组”是一个列,既不在_列中也不在_列2中。这是行不通的。如何在不同的列上执行不同的聚合函数?您已经非常接近了,不要将表达式放在列表中,而是将它们添加到一个表达式的平面列表中:
exprs=[u列中d的平均值(列(d)]+[u列中c的计数(列(c)]2]
下面是一个演示:
导入pyspark.sql.F函数
df.show()
+---+---+---+---+
|a | b | c | d|
+---+---+---+---+
| 1| 1| 2| 1|
| 1| 2| 2| 2|
| 2| 3| 3| 3|
| 2| 4| 3| 4|
+---+---+---+---+
cols=['b']
cols2=['c','d']
exprs=[F.mean(F.col(x))表示列中的x]+[F.count(F.col(x))表示列中的x]
df.groupBy('a').agg(*exprs.show())
+---+------+--------+--------+
|a |平均值(b)|计数(c)|计数(d)|
+---+------+--------+--------+
| 1| 1.5| 2| 2|
| 2| 3.5| 2| 2|
+---+------+--------+--------+
您已经非常接近了,不要将表达式放在列表中,而是将它们添加到一个表达式的平面列表中:
exprs=[u列中d的平均值(列(d)]+[u列中c的计数(列(c)]2]
下面是一个演示:
导入pyspark.sql.F函数
df.show()
+---+---+---+---+
|a | b | c | d|
+---+---+---+---+
| 1| 1| 2| 1|
| 1| 2| 2| 2|
| 2| 3| 3| 3|
| 2| 4| 3| 4|
+---+---+---+---+
cols=['b']
cols2=['c','d']
exprs=[F.mean(F.col(x))表示列中的x]+[F.count(F.col(x))表示列中的x]
df.groupBy('a').agg(*exprs.show())
+---+------+--------+--------+
|a |平均值(b)|计数(c)|计数(d)|
+---+------+--------+--------+
| 1| 1.5| 2| 2|
| 2| 3.5| 2| 2|
+---+------+--------+--------+