相关疑难解决方法(0)

Spark SQL:将聚合函数应用于列列表

有没有办法将聚合函数应用于数据帧的所有(或列表)列groupBy?换句话说,有没有办法避免为每一列执行此操作:

df.groupBy("col1")
  .agg(sum("col2").alias("col2"), sum("col3").alias("col3"), ...)
Run Code Online (Sandbox Code Playgroud)

aggregate-functions dataframe apache-spark apache-spark-sql

65
推荐指数
2
解决办法
12万
查看次数

将转换应用于多个列pyspark dataframe

假设我有以下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)

apache-spark apache-spark-sql pyspark pyspark-sql

4
推荐指数
1
解决办法
4454
查看次数