我在内存中加载了一个Spark DataFrame,我想对列进行均值(或任何聚合操作).我该怎么办?(在numpy,这被称为进行操作axis=1).
如果有人在行(axis=0)中计算DataFrame的平均值,那么这已经内置:
from pyspark.sql import functions as F
F.mean(...)
Run Code Online (Sandbox Code Playgroud)
但有没有办法以编程方式对列中的条目执行此操作?例如,从下面的DataFrame中
+--+--+---+---+
|id|US| UK|Can|
+--+--+---+---+
| 1|50| 0| 0|
| 1| 0|100| 0|
| 1| 0| 0|125|
| 2|75| 0| 0|
+--+--+---+---+
Run Code Online (Sandbox Code Playgroud)
省略id,手段将是
+------+
| mean|
+------+
| 16.66|
| 33.33|
| 41.67|
| 25.00|
+------+
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)