pyspark - 带有转置的pyspark列总和
问题描述
我有一个数据框看起来像 -
+---+---+---+---+
| id| w1| w2| w3|
+---+---+---+---+
| 1|100|150|200|
| 2|200|400|500|
| 3|500|600|150|
+---+---+---+---+
我希望输出看起来像 -
full total_amt
w1 800
w2 1150
w3 850
我的代码是 -
df = spark.createDataFrame(
[(1, 100,150,200), (2, 200,400,500), (3, 500,600,150)], ("id", "w1","w2","w3"))
res = df.unionAll(
df.select([
F.lit('All').alias('id'),
F.sum(df.w1).alias('w1'),
F.sum(df.w2).alias('w2'),
F.sum(df.w3).alias('w3')
]))
res.show()
But output gives me -
+---+---+----+---+
| id| w1| w2| w3|
+---+---+----+---+
| 1|100| 150|200|
| 2|200| 400|500|
| 3|500| 600|150|
|All|800|1150|850|
+---+---+----+---+
我认为添加后需要创建枢轴。所有字段本质上都是数字。
解决方案
一个快速的解决方案可能是
>>> df.createOrReplaceTempView('df')
>>> spark.sql('''
... select 'w1' as full, sum(w1) as total from df
... union
... select 'w2' as full, sum(w2) as total from df
... union
... select 'w3' as full, sum(w3) as total from df
... ''').show()
+----+-----+
|full|total|
+----+-----+
| w2| 1150|
| w3| 850|
| w1| 800|
+----+-----+
推荐阅读
- shell - 如何在makefile函数中传递逗号字符
- operator-overloading - 模棱两可的重载:运算符(类对象,int)
- c - Modbus 主从通讯
- javascript - 动态 HTML 容器
- r - 在数据帧之间找到相等的行,包括 NA 作为值
- appium - Ubuntu上的Appium桌面问题
- python - 如何解决 Resnet 模型中输出张量的值错误?
- mongodb - Mongo 从文档中的其他字段生成 id
- networking - 如何从客户端检测服务器 IP 并使用 TCP/IP 与该服务器连接?
- node.js - 使用 Buffer.allocUnsafe() 和 Buffer.alloc() 是什么情况?