gpt4 book ai didi

pandas - 从 Pandas groupBy 到 PySpark groupBy

转载 作者:行者123 更新时间:2023-12-02 03:19:13 32 4
gpt4 key购买 nike

考虑一个 Spark DataFrame,其中只有很少的列。目标是对其执行 groupBy 操作,而不将其转换为 Pandas DataFrame。等效的 Pandas groupBy 代码如下所示:

def compute_metrics(x):
return pd.Series({
'a': x['a'].values[0],
'new_b': np.sum(x['b']),
'c': np.mean(x['c']),
'cnt': len(x)
})

data.groupby([
'col_1',
'col_2'
]).apply(compute_metrics).reset_index()

我打算在 PySpark 中写这个。到目前为止,我在 PySpark 中想出了类似的东西:

gdf = df.groupBy([
'col_1',
'col_2'
]).agg({
'c': 'avg',
'b': 'sum'
}).withColumnRenamed('sum(b)', 'new_b')

但是,我不确定如何处理 'a': x['a'].values[0]'cnt': len(x)。我考虑过使用来自 pyspark.sql 导入函数的collect_list,但这让我的脸因Column object is not Callable而打脸。知道如何完成上述转换吗?谢谢!

[更新]任何列执行count操作以获得cnt是否有意义?假设我这样做:

gdf = df.groupBy([
'col_1',
'col_2'
]).agg({
'c': 'avg',
'b': 'sum',
'some_column': 'count'
}).withColumnRenamed('sum(b)', 'new_b')
.withColumnRenamed('count(some_column)', 'cnt')

最佳答案

我有一个使用 PySpark 函数 sumavgcountfirst 的玩具解决方案。 请注意,我在此解决方案中使用 Spark 2.1。希望这能有所帮助!

from pyspark.sql.functions import sum, avg, count, first

# create toy example dataframe with column 'A', 'B' and 'C'
ls = [['a', 'b',3], ['a', 'b', 4], ['a', 'c', 3], ['b', 'b', 5]]
df = spark.createDataFrame(ls, schema=['A', 'B', 'C'])

# group by column 'A' and 'B' then performing some function here
group_df = df.groupby(['A', 'B'])
df_grouped = group_df.agg(sum("C").alias("sumC"),
avg("C").alias("avgC"),
count("C").alias("countC"),
first("C").alias("firstC"))
df_grouped.show() # print out the spark dataframe

关于pandas - 从 Pandas groupBy 到 PySpark groupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42776610/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com