有没有办法将聚合函数应用于数据帧的所有(或列表)列groupBy?换句话说,有没有办法避免为每一列执行此操作:
df.groupBy("col1")
.agg(sum("col2").alias("col2"), sum("col3").alias("col3"), ...)
Run Code Online (Sandbox Code Playgroud) 假设我有以下spark-dataframe:
+-----+-------+
| word| label|
+-----+-------+
| red| color|
| red| color|
| blue| color|
| blue|feeling|
|happy|feeling|
+-----+-------+
Run Code Online (Sandbox Code Playgroud)
可以使用以下代码创建:
sample_df = spark.createDataFrame([
('red', 'color'),
('red', 'color'),
('blue', 'color'),
('blue', 'feeling'),
('happy', 'feeling')
],
('word', 'label')
)
Run Code Online (Sandbox Code Playgroud)
我可以执行a groupBy()来获取每个单词标签对的计数:
sample_df = sample_df.groupBy('word', 'label').count()
#+-----+-------+-----+
#| word| label|count|
#+-----+-------+-----+
#| blue| color| 1|
#| blue|feeling| 1|
#| red| color| 2|
#|happy|feeling| 1|
#+-----+-------+-----+
Run Code Online (Sandbox Code Playgroud)
然后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|
#+-----+-----+-------+
#| …Run Code Online (Sandbox Code Playgroud)