PySpark-对数据框中的一列求和并将结果作为int返回 [英] PySpark - Sum a column in dataframe and return results as int
问题描述
我有一个带数字列的pyspark数据框。我需要对该列求和,然后将结果作为int在python变量中返回。
I have a pyspark dataframe with a column of numbers. I need to sum that column and then have the result return as an int in a python variable.
df = spark.createDataFrame([("A", 20), ("B", 30), ("D", 80)],["Letter", "Number"])
我执行以下操作对列求和。
I do the following to sum the column.
df.groupBy().sum()
但是我得到了一个数据框。
But I get a dataframe back.
+-----------+
|sum(Number)|
+-----------+
| 130|
+-----------+
我会返回130作为存储在变量中的int值,以在程序中的其他位置使用。
I would 130 returned as an int stored in a variable to be used else where in the program.
result = 130
推荐答案
最简单的方法:
df.groupBy().sum().collect()
但是操作非常慢:避免使用groupByKey ,您应该使用RDD和reduceByKey:
But it is very slow operation: Avoid groupByKey, you should use RDD and reduceByKey:
df.rdd.map(lambda x: (1,x[1])).reduceByKey(lambda x,y: x + y).collect()[0][1]
我尝试使用更大的数据集并测量了处理时间:
I tried on a bigger dataset and i measured the processing time:
RDD和ReduceByKey: 2.23 s
RDD and ReduceByKey : 2.23 s
GroupByKey:30.5 s
GroupByKey: 30.5 s
这篇关于PySpark-对数据框中的一列求和并将结果作为int返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!