求和另一列返回 'col should be column error'

Sum over another column returning 'col should be column error'

我正在尝试添加一个新列,它根据 ID 列中的相应 ID 显示双精度(求和列)的总和。然而,这目前正在抛出 'col should be column error'

df = df.withColumn('sum_column', (df.groupBy('id').agg({'thing_to_sum': 'sum'})))

示例数据集:

| id | thing_to_sum | sum_column |
|----|--------------|------------
| 1  | 5            | 7          |
| 1  | 2            | 7          |
| 2  | 4            | 4          |

如有任何帮助,我们将不胜感激。

此外,任何有关执行此操作的最有效方法的参考资料也将不胜感激。

我认为我找到了自己问题的解决方案,但仍将不胜感激:

sum_calc = F.sum(df.thing_to_sum).over(Window.partitionBy("id"))
df = df.withColumn("sum_column", sum_calc)

您可以将任何 DataFrame 注册为临时 table 以通过 SQLContext.sql 查询它。

myValues = [(1,5),(1,2),(2,4),(2,3),(2,1)]
df = sqlContext.createDataFrame(myValues,['id','thing_to_sum'])
df.show()
+---+------------+
| id|thing_to_sum|
+---+------------+
|  1|           5|
|  1|           2|
|  2|           4|
|  2|           3|
|  2|           1|
+---+------------+
df.registerTempTable('table_view')
df1=sqlContext.sql(
    'select id, thing_to_sum, sum(thing_to_sum) over (partition by id) as sum_column from table_view'
)
df1.show()
+---+------------+----------+
| id|thing_to_sum|sum_column|
+---+------------+----------+
|  1|           5|         7|
|  1|           2|         7|
|  2|           4|         8|
|  2|           3|         8|
|  2|           1|         8|
+---+------------+----------+