在PySpark中大量订购

xuo3flqw  于 2023-11-16  发布在  Spark
关注(0)|答案(1)|浏览(101)

我有一个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  |
+----------+------------+----------------------------------------+-----------+---+


谢谢你

hvvq6cgz

hvvq6cgz1#

你可以按照你的价格列降序排序,转换为双精度型:

import pyspark.sql.functions as F
from pyspark.sql.window import Window

window = Window.orderBy(F.col("price").astype("double").desc())
df_product_updates.withColumn("rn", F.row_number().over(window)).show(truncate=False)

+----------+------------+----------------------------------------+-----------+---+
|product_id|product_name|price                                   |category   |rn |
+----------+------------+----------------------------------------+-----------+---+
|00001     |Heater      |1111111111111111111111111111111111111111|Electronics|1  |
|00007     |Desk        |60                                      |Furniture  |2  |
|00006     |Chair       |50                                      |Furniture  |3  |
+----------+------------+----------------------------------------+-----------+---+

字符串
请注意,这里我只是按转换的列排序,最终的架构仍然具有原始模式(因此price列仍然是StringType
如果你想使用SQL,你可以这样做:

df_sort_price = spark.sql(
    f"""
    select *, row_number() over (order by cast(price as double) desc) rn
    from sort_price
"""
)

相关问题