【问题标题】:Not able to fetch all the columns while using groupby in pyspark在 pyspark 中使用 groupby 时无法获取所有列
【发布时间】:2018-01-30 00:42:42
【问题描述】:
columnList = [item[0] for item in df1.dtypes if item[1].startswith('string')]

df2 = df1.groupBy("TCID",columnList).agg(mean("Runtime").alias("Runtime"))

这样使用时出现以下错误:

py4j.protocol.Py4JError: An error occurred while calling    z:org.apache.spark.sql.functions.col. Trace:
py4j.Py4JException: Method col([class java.util.ArrayList]) does not exist
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:339)
at py4j.Gateway.invoke(Gateway.java:274)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Thread.java:748)

【问题讨论】:

  • 试试df2 = df1.groupBy(["TCID"] + columnList) ...
  • 感谢@pault,它工作正常。如何从 columnList 中删除 TCID
  • 使用df.select(columnList) 选择您想要的列。如果这不是你的意思,你能举一个你想要的输出的例子吗?更多信息:How to make good reproducible apache spark examples
  • 我在 columnList 中有 TCID。我将 TCID 作为 groupBy 提供,因此它在结果中显示了两次。可以去掉吗?
  • 您要按哪一列分组?只有 TCID,还是所有列?请尝试提供一个小例子。

标签: pyspark pyspark-sql


【解决方案1】:

docs pyspark.sql.DataFrame.groupBy 接收“要分组的列列表。

您的代码失败,因为第二个参数 (columnList) 不是有效的列标识符。因此出现错误:col([class java.util.ArrayList]) does not exist

相反,您可以执行以下操作:

df2 = df1.groupBy(["TCID"] + columnList).agg(mean("Runtime").alias("Runtime"))

或者同等地,并且更容易阅读 IMO:

columnList = [item[0] for item in df1.dtypes if item[1].startswith('string')]
groupByColumns = ["TCID"] + columnList
df2 = df1.groupBy(groupByColumns).agg(mean("Runtime").alias("Runtime"))

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多