首页 > 解决方案 > 为分组的 pyspark 数据框创建多列

问题描述

我正在尝试向我的数据框添加几个新列(最好在 for 循环中),每个新列都是 的某些实例的计数 col B,在分组后column A

什么不起作用:

import functions as f
#the first one will be fine
df_grouped=df.select('A','B').filter(df.B=='a').groupBy('A').count()
df_grouped.show()
+---+-----+
| A |count|
+---+-----+
|859|    4|
|947|    2|
|282|    6|
|699|   24|
|153|   12|

# create the second column:
df_g2=df.select('A','B').filter(df.B=='b').groupBy('A').count() 
df_g2.show()
+---+-----+
| A |count|
+---+-----+
|174|   18|
|153|   20|
|630|    6|
|147|   16|

#I get an error on adding the new column:
df_grouped=df_grouped.withColumn('2nd_count',f.col(df_g2.select('count')))

错误:

AttributeError:“DataFrame”对象没有属性“_get_object_id”

我也尝试过不使用f.col, 和 just df_g2.count,但我收到一条错误消息,说“col 应该是列”。

确实有效的东西:

df_g1=df.select('A','B').filter(df.B=='a').groupBy('A').count()
df_g2=df.select('A','B').filter(df.B=='b').groupBy('A').count()
df_grouped=df_g1.join(df_g2,['A'])  

但是,我将添加大约 1000 个新列,并且拥有这么多的连接似乎代价高昂。我想知道是否进行连接是不可避免的,因为每次我 group bycol A时,它在分组对象中的顺序都会发生变化(例如,比较column Adf_grouped 中的顺序与df_g2上面的顺序),或者有更好的方法来做到这一点。

标签: dataframegroup-bypyspark

解决方案


您可能需要的是groupbyand pivot。试试这个:

df.groupby('A').pivot('B').agg(F.count('B')).show()

推荐阅读