dataframe - 为分组的 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 A
df_grouped 中的顺序与df_g2
上面的顺序),或者有更好的方法来做到这一点。
解决方案
您可能需要的是groupby
and pivot
。试试这个:
df.groupby('A').pivot('B').agg(F.count('B')).show()
推荐阅读
- python - Apache Beam 到 BigQuery
- r - 在没有内置函数的情况下计算 R 中的均值和方差(硬件问题)
- python-3.x - 如何通过从多个数组中选择 h/l 值来生成随机均匀分布?
- forms - 有没有办法根据 MS 访问表单上的其他输入创建序列号?
- javascript - ES 动态导入,Safari 上的 ChunkLoadError
- angular - 角度:如何处理角度材料表中的空值
- node.js - Nodejs用HTTP get下载tar.gz文件
- c# - Visual Studio Code 不会自动完成我的 C# 代码
- python - 如何在没有 href 的情况下单击“a”标签,以在抓取所有评论之前加载更多评论 - Web Scraping (Python)
- excel - 复制并粘贴带有特定子句的单元格