python - PySpark:具有多个功能的多列上的 Groupby

标签 python apache-spark pyspark

我正在使用 Spark 2.0 运行 PySpark 来聚合数据。 下面是 Spark 中收到的原始数据帧 (df)。

DeviceID    TimeStamp           IL1    IL2    IL3    VL1    VL2    VL3
1001        2019-07-14 00:45    2.1    3.1   2.25    235    258    122
1002        2019-07-14 01:15    3.2    2.4   4.25    240    250    192
1003        2019-07-14 01:30    3.2    2.0   3.85    245    215    192
1003        2019-07-14 01:30    3.9    2.8   4.25    240    250    192

现在我想通过 DeviceID 应用 groupby 逻辑。 StackOverflow 中有几篇文章。特别是Thisthis链接是感兴趣的点。在这些帖子的帮助下,我创建了以下脚本

from pyspark.sql import functions as F
groupby = ["DeviceID"]
agg_cv = ["IL1","IL2","IL3","VL1","VL2","VL3"]
func = [min,max]
expr_cv = [F.f(F.col(c)) for f in func for c in agg_cv]
df_final = df_cv_filt.groupby(*groupby).agg(*expr_cv)

上面的代码显示错误为

Columns are not iterable 

无法理解为什么会出现这样的错误。当我使用以下代码时

from pyspark.sql.functions import min, max, col
expr_cv = [f(col(c)) for f in func for c in agg_cv]

那么上面的代码就可以正常运行了。

我的问题是:如何修复上述错误。

最佳答案

尝试使用

func = [F.min,F.max]
agg_cv = ["IL1","IL2","IL3","VL1","VL2","VL3"]
expr_cv = [f(F.col(c)) for f in func for c in agg_cv]
df_final = df1.groupby(*groupby).agg(*expr_cv)

这应该有效。

+--------+---------+--------+--------+--------+--------+--------+---------+--------+--------+--------+--------+--------+
|DeviceID|min( IL1)|min(IL2)|min(IL3)|min(VL1)|min(VL2)|min(VL3)|max( IL1)|max(IL2)|max(IL3)|max(VL1)|max(VL2)|max(VL3)|
+--------+---------+--------+--------+--------+--------+--------+---------+--------+--------+--------+--------+--------+
|    1003|      3.2|     2.0|    3.85|     240|     215|     192|      3.9|     2.8|    4.25|     245|     250|     192|
|    1002|      3.2|     2.4|    4.25|     240|     250|     192|      3.2|     2.4|    4.25|     240|     250|     192|
|    1001|      2.1|     3.1|    2.25|     235|     258|     122|      2.1|     3.1|    2.25|     235|     258|     122|
+--------+---------+--------+--------+--------+--------+--------+---------+--------+--------+--------+--------+--------+```

关于python - PySpark:具有多个功能的多列上的 Groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053789/

相关文章:

python - 在 PyTorch 中将值从一个张量复制到另一个张量的最快方法是什么?

scala - Apache Spark 使用管道分隔的 CSV 文件

azure - 我的 Azure Synapse 笔记本已成功完成,但收到错误 "Error code 1 EXCEPTION_DURING_SPARK_JOB_CLEANUP"

python - 在 apache zeppelin 中找不到 pyspark 解释器

python - 如何在 python 2.7 中执行此 CURL 以从 Elasticsearch 中删除文档?

python - 将 http header (字符串)转换为 python 字典

python - django-south 迁移期间出错

apache-spark - 为什么Spark应用程序未在所有节点上运行

python - PySpark 1.5 如何将时间戳从秒截断到最近的分钟

hadoop - Pyspark 操作提交时 oozie 失败 : '[Errno 2] No such file or directory'