有两种简单的方法可以做到这一点。第一种就是简单地使用
+
输入列名,另一个使用
add
和
reduce
一次对许多列求和。
下面是一个示例,其中显示了两种方法来获取具有
x
以他们的名义(所以我们不包括列
y1
全部进出)。
希望这有帮助!
import pyspark.sql.functions as F
import pandas as pd
# SAMPLE DATA -----------------------------------------------------------------------
df = pd.DataFrame({'x1': [0,0,0,1,1],
'x2': [6,5,4,3,2],
'x3': [2,2,2,2,2],
'y1': [1,1,1,1,1]})
df = spark.createDataFrame(df)
# Sum by typing the column names explicitly
df = df.withColumn('total_1',F.col('x1') + F.col('x2') + F.col('x3'))
# Sum many columns without typing them out using reduce
import operator
import functools
cols_to_sum = [col for col in df.columns if 'x' in col]
df = df.withColumn('total_2',functools.reduce(operator.add, [F.col(x) for x in cols_to_sum]))
df.show()
输出:
+---+---+---+---+-------+-------+
| x1| x2| x3| y1|total_1|total_2|
+---+---+---+---+-------+-------+
| 0| 6| 2| 1| 8| 8|
| 0| 5| 2| 1| 7| 7|
| 0| 4| 2| 1| 6| 6|
| 1| 3| 2| 1| 6| 6|
| 1| 2| 2| 1| 5| 5|
+---+---+---+---+-------+-------+