在pyspark中使用groupby时无法获取所有列

时间:2018-01-29 15:45:16

标签: pyspark pyspark-sql

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)

1 个答案:

答案 0 :(得分:2)

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"))