在 Pandas 上,我們可以按類別系列分組,然后在聚合時顯示所有類別,無論它是否包含任何記錄。
import pandas as pd
df = pd.DataFrame({"Age": [12, 20, 40, 60, 72]}, dtype=np.float64)
cuts = pd.cut(df.Age, bins=[0, 11, 30, 60])
df.Age.groupby(cuts).agg(mean="mean", occurrences="size")
# mean occurrences
# Age
# (0, 11] NaN 0
# (11, 30] 16.0 2
# (30, 60] 50.0 2
如您所見,即使第一個 bin 沒有出現在資料集中,它也會顯示出來。我怎樣才能在 PySpark 上實作相同的行為?
uj5u.com熱心網友回復:
以下內容相當多,但我不知道有什么更好的方法。
from pyspark.sql import functions as F
df = spark.createDataFrame([(12,), (20,), (40,), (60,), (72,)], ['Age'])
bins = [0, 11, 30, 60]
conds = F
for i, b in enumerate(bins[1:]):
conds = conds.when(F.col('id') <= b, f'({bins[i]}, {b}]')
df2 = spark.range(1, bins[-1] 1).withColumn('_grp', conds)
df = df2.join(df, df2.id == df.Age, 'left')
df = df.groupBy(F.col('_grp').alias('Age')).agg(
F.mean('Age').alias('mean'),
F.count('Age').alias('occurrences'),
)
df.show()
# -------- ---- -----------
# | Age|mean|occurrences|
# -------- ---- -----------
# |(11, 30]|16.0| 2|
# | (0, 11]|null| 0|
# |(30, 60]|50.0| 2|
# -------- ---- -----------
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/519590.html
標籤:Python阿帕奇火花pyspark通过...分组分组
