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

标签 python-2.7 apache-spark pivot 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"])

这使
+-------+--------------------+------------+
|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/

相关文章:

python - 在 Python 中执行访问单独数据库的 MySQL 查询

Python:嵌套列表中的第一个元素

python - 溢出 : length too large

apache-spark - 如何列出添加到 spark 上下文的 spark-packages?

map 内的Scala Spark过滤器

MYSQL创建动态数据透视表

python - 键盘事件未使用 pywin32 发送到窗口

python - Spyder IDE 看不到 pyspark 模块

Python 分组依据和带有空格的求和

sql - 如何将选择查询结果插入 PIVOT