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

hyp*_*c54 6 pivot python-2.7 apache-spark pyspark pyspark-sql

我正在尝试对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"])
Run Code Online (Sandbox Code Playgroud)

这使

+-------+--------------------+------------+
|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'     |
Run Code Online (Sandbox Code Playgroud)

问题是打电话

df = df.groupby('user_id')\
       .pivot('actions')\
       .agg(func.count('timestamp').alias('ts_count'),
            func.mean('timestamp').alias('ts_mean'))
Run Code Online (Sandbox Code Playgroud)

给出列名

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']
Run Code Online (Sandbox Code Playgroud)

这是完全不切实际的.

我可以使用这里显示的方法清理我的列名- (正则表达式)这里 - (使用withColumnRenamed().但是这些是更新后很容易破解的解决方法.

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

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

小智 0

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

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

@hyperc54