我有一个 PySpark 数据框,其中有一个很大的数字(最多 40 位数字)的字符串列。我的目标是对其进行排序。我尝试转换为十进制,但如果数字超过 38 位,则不起作用。这是一个示例数据框来说明该问题。
from pyspark.sql import Row
# Column price has a 40 digit number.
product_updates = [
{'product_id': '00001', 'product_name': 'Heater', 'price': '1111111111111111111111111111111111111111', 'category': 'Electronics'},
{'product_id': '00006', 'product_name': 'Chair', 'price': '50', 'category': 'Furniture'},
{'product_id': '00007', 'product_name': 'Desk', 'price': '60', 'category': 'Furniture'}
]
df_product_updates = spark.createDataFrame(Row(**x) for x in product_updates)
# Order by price
df_product_updates.createOrReplaceTempView("sort_price")
df_sort_price = spark.sql(f"""
select *,
row_number() over (order by price DESC) rn
from sort_price
""")
df_sort_price.show(truncate=False)
有没有办法比较数字,使最大的排为1?
+----------+------------+----------------------------------------+-----------+---+
|product_id|product_name|price |category |rn |
+----------+------------+----------------------------------------+-----------+---+
|00007 |Desk |60 |Furniture |1 |
|00006 |Chair |50 |Furniture |2 |
|00001 |Heater |1111111111111111111111111111111111111111|Electronics|3 |
+----------+------------+----------------------------------------+-----------+---+
谢谢你
您可以按降序排列将价格列转换为双精度:
import pyspark.sql.functions as F
df_product_updates.orderBy(F.col("price").astype("double").desc()).show(truncate=False)
+----------+------------+----------------------------------------+-----------+
|product_id|product_name|price |category |
+----------+------------+----------------------------------------+-----------+
|00001 |Heater |1111111111111111111111111111111111111111|Electronics|
|00007 |Desk |60 |Furniture |
|00006 |Chair |50 |Furniture |
+----------+------------+----------------------------------------+-----------+
请注意,这里我只是按铸造列排序,最终的数据框仍然具有原始架构(因此您的
price
列仍然是StringType
)