PySpark - 在数据框中求和一列并将结果返回为 int

2022-11-05Python开发问题
34

本文介绍了Pyspark - 在数据框中求和一列并将结果返回为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个带有一列数字的 pyspark 数据框.我需要对该列求和,然后将结果返回为 python 变量中的 int.

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 秒

RDD and ReduceByKey : 2.23 s

GroupByKey:30.5 秒

GroupByKey: 30.5 s

这篇关于PySpark - 在数据框中求和一列并将结果返回为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End
spa

相关推荐

Bot前缀中的空格
Space in the Bot Prefix(Bot前缀中的空格)...
2024-08-22 Python开发问题
2

从范围获取文本返回空字符串
Get Text from Span returns empty string(从范围获取文本返回空字符串)...
2024-08-21 Python开发问题
13

Seborn FactGrid子图的一个共享x轴标签(布局/间距?)
One shared x-axis label for Seaborn FacetGrid subplots (layouts/spacing?)(Seborn FactGrid子图的一个共享x轴标签(布局/间距?))...
2024-08-20 Python开发问题
1

为什么不能从方法访问类变量?
Why is a class variable not accessible from a method?(为什么不能从方法访问类变量?)...
2024-08-11 Python开发问题
2

Python中的子句提取/长句切分
Clause extraction / long sentence segmentation in python(Python中的子句提取/长句切分)...
2024-08-11 Python开发问题
12

pysppark&39;s"BETWEEN"函数:时间戳上的范围搜索不包括在
pyspark#39;s quot;betweenquot; function: range search on timestamps is not inclusive(pysppark39;squot;BETWEENQUOT;函数:时间戳上的范围搜索不包括在内)...
2024-08-10 Python开发问题
2