首页 > 解决方案 > Sum() 和 count() 在 pyspark2 中不能与 agg 一起使用

问题描述

我正在使用 json 数据文件“order_items”,数据看起来像

{“order_item_id”:1,“order_item_order_id”:1,“order_item_product_id”:957,“order_item_quantity”:1,“order_item_subtotal”:299.98,“order_item_product_price”:299.98}
{“order_item_id”:2,“order_item_order_id”:2,“order_item_product_id”:1073,“order_item_quantity”:1,“order_item_subtotal”:199.99,“order_item_product_price”:199.99}
{“order_item_id”:3,“order_item_order_id”:2,“order_item_product_id”:502,“order_item_quantity”:5,“order_item_subtotal”:250.0,“order_item_product_price”:50.0}
{“order_item_id”:4,“order_item_order_id”:2,“order_item_product_id”:403,“order_item_quantity”:1,“order_item_subtotal”:129.99,“order_item_product_price”:129.99}

orders = spark.read.json("/user/data/retail_db_json/order_items")

运行以下命令时出现错误。

orders.where("order_item_order_id in( 2,4,5,6,7,8,9,10) ").groupby(“order_item_order_id”).agg(sum(“order_item_subtotal”),count()).orderBy(“order_item_order_id”).show()

类型错误:+ 的不支持的操作数类型:'int' 和 'str'</p>

我不知道为什么我会得到......所有列值都是字符串。有什么建议吗?

标签: pyspark

解决方案


将列转换为 int 类型。不能对字符串类型应用聚合方法。


推荐阅读