MrG*_*rts 4 python group-by mapreduce apache-spark
我在数据帧中使用 Spark 1.6.2
我想转换这个数据帧
+---------+-------------+-----+-------+-------+-------+-------+--------+
|ID | P |index|xinf |xup |yinf |ysup | M |
+---------+-------------+-----+-------+-------+-------+-------+--------+
| 0|10279.9003906| 13| 0.3| 0.5| 2.5| 3.0|540928.0|
| 2|12024.2998047| 13| 0.3| 0.5| 2.5| 3.0|541278.0|
| 0|10748.7001953| 13| 0.3| 0.5| 2.5| 3.0|541243.0|
| 1| 10988.5| 13| 0.3| 0.5| 2.5| 3.0|540917.0|
+---------+-------------+-----+-------+-------+-------+-------+--------+
Run Code Online (Sandbox Code Playgroud)
到
+---------+-------------+-----+-------+-------+-------+-------+--------+
|Id | P |index|xinf |xup |yinf |ysup | M |
+---------+-------------+-----+-------+-------+-------+-------+--------+
| 0|10514.3002929| 13| 0.3| 0.5| 2.5| 3.0|540928.0,541243.0|
| 2|12024.2998047| 13| 0.3| 0.5| 2.5| 3.0|541278.0|
| 1| 10988.5| 13| 0.3| 0.5| 2.5| 3.0|540917.0|
+---------+-------------+-----+-------+-------+-------+-------+--------+
Run Code Online (Sandbox Code Playgroud)
所以,我想减少 Id,并计算 P 行的平均值并连接 M 行。但是我不能使用 spark 的函数 agg 来做到这一点。
你能帮我吗
你可以groupBy列ID,然后汇总每列取决于你需要什么,mean并concat会帮助你。
from pyspark.sql.functions import first, collect_list, mean
df.groupBy("ID").agg(mean("P"), first("index"),
first("xinf"), first("xup"),
first("yinf"), first("ysup"),
collect_list("M"))
Run Code Online (Sandbox Code Playgroud)