python - 在 PySpark Dataframe 中结合旋转和分组聚合
问题描述
我正在重新使用PySpark Dataframe 中组合旋转和聚合列中的示例
假设我有一个 Spark 数据框
date | recipe | percent | volume
----------------------------------------
2019-01-01 | A | 0.03 | 53
2019-01-01 | A | 0.02 | 55
2019-01-01 | B | 0.05 | 60
2019-01-02 | A | 0.11 | 75
2019-01-02 | B | 0.06 | 64
2019-01-02 | B | 0.08 | 66
如何像以下伪代码一样以一列为中心并在另一列上聚合:
df.groupBy('date').max('volume').alias('max_volume').pivot('recipe').agg(avg('percent').alias('percent')).show()
date | A_percent | B_percent | max_volume
--------------------------------------------------------
2019-01-01 | 0.025 | 0.05 | 60
2019-01-02 | 0.11 | 0.07 | 75
我想一步实现这一点,而不必稍后对列 A_volume 和 B_volume 执行 max 以避免命名这些列。
附言。当我本机运行该伪代码时,我得到
AttributeError: 'DataFrame' object has no attribute 'pivot'
解决方案
尝试这个:
from pyspark.sql.functions import *
from pyspark.sql import Window
var win = Window.partitionBy("date")
data.withColumn("max_vol",max("volume").over(win)).groupBy("date","max_vol") .pivot("recipe") .agg(avg("percent")).show()
推荐阅读
- c - 为什么将 &str 转换为 *const i8,将其发送到 C 或从 C 发送,然后再转换回 &str 会导致 Utf8Error?
- python - python图中的3d效果
- java - 如何将手机铃声重置为系统默认设置?
- istio - 上游连接错误或在标头之前断开/重置。重置原因:连接失败
- php - 为 WooCommerce 产品属性创建自定义按钮
- java - 如何将文件本身作为项目处理?
- ubuntu - 主管使用所有 cpu 电源
- reactjs - 为什么 useEffect 不直接支持异步回调或者清理函数有单独的参数?
- amazon-web-services - AWS Cognito 错误:没有为未经身份验证的访问提供 Cognito 身份池
- python - python中TCP套接字中两个客户端之间的简单数据传输