如何在PySpark中的数据帧内按和排序?

2024-09-27 00:11:21 发布

您现在位置:Python中文网/ 问答频道 /正文

类似于:

order_items.groupBy("order_item_order_id").count().orderBy(desc("count")).show()

我试过:

order_items.groupBy("order_item_order_id").sum("order_item_subtotal").orderBy(desc("sum")).show()

但这会产生一个错误:

Py4JJavaError: An error occurred while calling o501.sort. : org.apache.spark.sql.AnalysisException: cannot resolve 'sum' given input columns order_item_order_id, SUM(order_item_subtotal#429);

我也试过:

order_items.groupBy("order_item_order_id").sum("order_item_subtotal").orderBy(desc("SUM(order_item_subtotal)")).show()

但我也犯了同样的错误:

Py4JJavaError: An error occurred while calling o512.sort. : org.apache.spark.sql.AnalysisException: cannot resolve 'SUM(order_item_subtotal)' given input columns order_item_order_id, SUM(order_item_subtotal#429);

我在执行时得到正确的结果:

order_items.groupBy("order_item_order_id").sum("order_item_subtotal").orderBy(desc("SUM(order_item_subtotal#429)")).show()

但这是在看到Spark附加在sum列名称后面的数字(即429)之后进行的。

有没有一种方法可以得到相同的结果,但却不知道要追加哪个数字,而是先验的结果?


Tags: anidshowcount错误orderitemsitem
1条回答
网友
1楼 · 发布于 2024-09-27 00:11:21

您应该为列使用别名:

import pyspark.sql.functions as func

order_items.groupBy("order_item_order_id")\
           .agg(func.sum("order_item_subtotal")\
                .alias("sum_column_name"))\
           .orderBy("sum_column_name")

相关问题 更多 >

    热门问题