如何对pyspark中的spark数据帧中的多列求和? [英] How can I sum multiple columns in a spark dataframe in pyspark?
本文介绍了如何对pyspark中的spark数据帧中的多列求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个要汇总的列名列表
I've got a list of column names I want to sum
columns = ['col1','col2','col3']
如何添加这三个并将其放入新列中?(以自动方式,以便我可以更改列列表并获得新结果)
How can I add the three and put it in a new column ? (in an automatic way, so that I can change the column list and have new results)
带有我想要的结果的数据框:
Dataframe with result I want:
col1 col2 col3 result
1 2 3 6
推荐答案
试试这个:
df = df.withColumn('result', sum(df[col] for col in df.columns))
df.columns
将是来自 df 的列列表.
df.columns
will be list of columns from df.
这篇关于如何对pyspark中的spark数据帧中的多列求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文