gpt4 book ai didi

python-2.7 - Pyspark 1.6 - 使用多个聚合旋转后的别名列

转载 作者:行者123 更新时间:2023-12-04 15:53:22 25 4
gpt4 key购买 nike

我目前正在尝试对在 Pyspark 数据帧上的值进行旋转后得到的列进行别名。这里的问题是我放在别名调用中的列名没有正确设置。

一个具体的例子:

从这个数据帧开始:

import pyspark.sql.functions as func

df = sc.parallelize([
(217498, 100000001, 'A'), (217498, 100000025, 'A'), (217498, 100000124, 'A'),
(217498, 100000152, 'B'), (217498, 100000165, 'C'), (217498, 100000177, 'C'),
(217498, 100000182, 'A'), (217498, 100000197, 'B'), (217498, 100000210, 'B'),
(854123, 100000005, 'A'), (854123, 100000007, 'A')
]).toDF(["user_id", "timestamp", "actions"])

这使
+-------+--------------------+------------+
|user_id| timestamp | actions |
+-------+--------------------+------------+
| 217498| 100000001| 'A' |
| 217498| 100000025| 'A' |
| 217498| 100000124| 'A' |
| 217498| 100000152| 'B' |
| 217498| 100000165| 'C' |
| 217498| 100000177| 'C' |
| 217498| 100000182| 'A' |
| 217498| 100000197| 'B' |
| 217498| 100000210| 'B' |
| 854123| 100000005| 'A' |
| 854123| 100000007| 'A' |

问题是调用
df = df.groupby('user_id')\
.pivot('actions')\
.agg(func.count('timestamp').alias('ts_count'),
func.mean('timestamp').alias('ts_mean'))

给出列名
df.columns

['user_id',
'A_(count(timestamp),mode=Complete,isDistinct=false) AS ts_count#4L',
'A_(avg(timestamp),mode=Complete,isDistinct=false) AS ts_mean#5',
'B_(count(timestamp),mode=Complete,isDistinct=false) AS ts_count#4L',
'B_(avg(timestamp),mode=Complete,isDistinct=false) AS ts_mean#5',
'C_(count(timestamp),mode=Complete,isDistinct=false) AS ts_count#4L',
'C_(avg(timestamp),mode=Complete,isDistinct=false) AS ts_mean#5']

这是完全不切实际的。

我可以使用显示的方法清理我的列名 here - (regex)
here - (use of withColumnRenamed() .
然而,这些是在更新后很容易中断的变通方法。

总结一下:如何使用数据透视生成的列而不必解析它们? (例如 'A_(count(timestamp),mode=Complete,isDistinct=false) AS ts_count#4L' 生成的名称)?

任何帮助,将不胜感激 !
谢谢

最佳答案

发生这种情况是因为您要旋转的列没有不同的值。当数据透视发生时,这会导致重复的列名,因此 spark 为它提供这些列名以使其不同。您需要在透视之前对透视列进行分组以使透视列(操作)中的值不同。

如果您需要更多帮助,请告诉我!

@hyperc54

关于python-2.7 - Pyspark 1.6 - 使用多个聚合旋转后的别名列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41832734/

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