【发布时间】:2018-09-12 23:42:47
【问题描述】:
假设我有以下 spark-dataframe:
+-----+-------+
| word| label|
+-----+-------+
| red| color|
| red| color|
| blue| color|
| blue|feeling|
|happy|feeling|
+-----+-------+
可以使用以下代码创建:
sample_df = spark.createDataFrame([
('red', 'color'),
('red', 'color'),
('blue', 'color'),
('blue', 'feeling'),
('happy', 'feeling')
],
('word', 'label')
)
我可以执行groupBy() 来获取每个单词标签对的计数:
sample_df = sample_df.groupBy('word', 'label').count()
#+-----+-------+-----+
#| word| label|count|
#+-----+-------+-----+
#| blue| color| 1|
#| blue|feeling| 1|
#| red| color| 2|
#|happy|feeling| 1|
#+-----+-------+-----+
然后pivot() 和sum() 将标签计数为列:
import pyspark.sql.functions as f
sample_df = sample_df.groupBy('word').pivot('label').agg(f.sum('count')).na.fill(0)
#+-----+-----+-------+
#| word|color|feeling|
#+-----+-----+-------+
#| red| 2| 0|
#|happy| 0| 1|
#| blue| 1| 1|
#+-----+-----+-------+
转换此dataframe 以使每一行除以该行的总数的最佳方法是什么?
# Desired output
+-----+-----+-------+
| word|color|feeling|
+-----+-----+-------+
| red| 1.0| 0.0|
|happy| 0.0| 1.0|
| blue| 0.5| 0.5|
+-----+-----+-------+
实现此结果的一种方法是使用__builtin__.sum(不是pyspark.sql.functions.sum)获取逐行总和,然后为每个标签调用withColumn():
labels = ['color', 'feeling']
sample_df.withColumn('total', sum([f.col(x) for x in labels]))\
.withColumn('color', f.col('color')/f.col('total'))\
.withColumn('feeling', f.col('feeling')/f.col('total'))\
.select('word', 'color', 'feeling')\
.show()
但必须有比枚举每个可能的列更好的方法。
更一般地说,我的问题是:
如何将任意转换(即当前行的函数)同时应用于多列?
【问题讨论】:
标签: apache-spark pyspark apache-spark-sql pyspark-sql