use*_*579 2 python apache-spark pyspark
有一种求DF中行总和的场景如下
ID DEPT [..] SUB1 SUB2 SUB3 SUB4 **SUM1**
1 PHY 50 20 30 30 130
2 COY 52 62 63 34 211
3 DOY 53 52 53 84
4 ROY 56 52 53 74
5 SZY 57 62 73 54
Run Code Online (Sandbox Code Playgroud)
需要找到每一行的 SUB1 SUB2 SUB3 SUB4 的行总和,并将其作为新列 SUM1。数据帧中 SUB1 列的序号位置为 16。
您可以使用 Pythonsum将列相加:
import pyspark.sql.functions as F
col_list = ['SUB1', 'SUB2', 'SUB3', 'SUB4']
# or col_list = df.columns[16:20]
df2 = df.withColumn(
'SUM1',
sum([F.col(c) for c in col_list])
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12230 次 |
| 最近记录: |