假设我有一个表(df),如下所示:
type count
A 5000
B 5000
C 200
D 123
... ...
... ...
Z 453如何将列count按类型A、B和所有其他类型归入Others类别进行求和?
我目前有这个:
df = df.withColumn('type', when(col("type").isnot("A", "B"))我的预期输出将如下所示:
type count
A 5000
B 5000
Other 3043发布于 2021-02-24 01:04:31
您希望group by when表达式并对计数求和:
from pyspark.sql import functions as F
df1 = df.groupBy(
when(
F.col("type").isin("A", "B"), F.col("type")
).otherwise("Others").alias("type")
).agg(
F.sum("count").alias("count")
)
df1.show()
#+------+-----+
#| type|count|
#+------+-----+
#| B| 5000|
#| A| 5000|
#|Others| 776|
#+------+-----+发布于 2021-02-24 01:14:23
您可以根据类型将数据帧划分为两个部分,为第二部分汇总总和,然后执行unionAll将它们组合在一起。
import pyspark.sql.functions as F
result = df.filter("type in ('A', 'B')").unionAll(
df.filter("type not in ('A', 'B')")
.select(F.lit('Other'), F.sum('count'))
)
result.show()
+-----+-----+
| type|count|
+-----+-----+
| A| 5000|
| B| 5000|
|Other| 776|
+-----+-----+https://stackoverflow.com/questions/66337545
复制相似问题