Pyspark 将多个列合并为一个 json 列,其列名与 dataframe 不同

问题描述 投票:0回答:0

我有一个像这样的pyspark数据框(df):

产品 地区 订购日期 费用 收入 利润
P1 R1 2023 年 3 月 1 日 500 600 100
P1 R1 2022 年 12 月 1 日 400 450 50
P2 R1 2023 年 3 月 1 日 500 600 100
P2 R1 2022 年 12 月 1 日 600 800 200

我正在尝试使用以下代码查找最近 3 个月和最近 6 个月的详细信息。

aggr_df = spark.sql(f"""
    SELECT 
        product,
        region,
        SUM(CASE WHEN reporting_period_date >= '{last_3m_first_day}'  THEN cost     ELSE 0 END) last_3m_cost   ,
        SUM(CASE WHEN reporting_period_date >= '{last_3m_first_day}'  THEN revenue  ELSE 0 END) last_3m_revenue,
        SUM(CASE WHEN reporting_period_date >= '{last_3m_first_day}'  THEN profit   ELSE 0 END) last_3m_profit ,
        SUM(CASE WHEN reporting_period_date >= '{last_6m_first_day}'  THEN cost     ELSE 0 END) last_6m_cost   ,
        SUM(CASE WHEN reporting_period_date >= '{last_6m_first_day}'  THEN revenue  ELSE 0 END) last_6m_revenue,
        SUM(CASE WHEN reporting_period_date >= '{last_6m_first_day}'  THEN profit   ELSE 0 END) last_6m_profit 
    FROM 
        fact
    GROUP BY 
        product,
        region
    """)

这里 last_3m_first_day , last_6m_first_day 分别是过去 3 个月和 6 个月的第一天。

我得到以下输出。

产品 地区 Last_3M_Cost Last_3M_Revenue Last_3M_Profit Last_6M_Cost Last_6M_Revenue Last_6M_Profit
P1 R1 500 600 100 900 1050 150
P2 R1 500 600 100 1100 1400 300

我在这里尝试将 6 个事实数据转换为单个 json 数据,如下所示。

产品 地区 Last_Month_Details
P1 R1 {"3_MONTHS":"{"成本":500,"收入":600,"利润":100}","6_MONTHS":"{"成本":900,"收入":1050,"利润": 150}"}
P2 R1 {"3_MONTHS":"{"成本":500,"收入":600,"利润":100}","6_MONTHS":"{"成本":1100,"收入":1400,"利润": 300}"}

如何我无法实现上述格式。我试过下面的代码。

    aggr_temp_df = aggr_df.select \
        ("product","region", \
         to_json(struct("last_3m_cost","last_3m_revenue","last_3m_profit")).alias("3_MONTHS"), \
         to_json(struct("last_6m_cost","last_6m_revenue","last_6m_profit")).alias("6_MONTHS") \
        )
    
    final_aggr_df = aggr_temp_df.select \
        ("product","region", \
         to_json(struct("3_MONTHS","6_MONTHS")).alias("monthly_aggregate_totals") \
        )

我得到以下输出。这里唯一的区别是我无法将数据框列更改为不同的列。 例如:last_3m_cost 到 cost,last_3m_revenue 到 revenue。

产品 地区 Last_Month_Details
P1 R1 {"3_MONTHS":"{"Last_3M_Cost":500,"Last_3M_Revenue":600,"Last_3M_Profit":100}","6_MONTHS":"{"Last_6M_Cost":900,"Last_6M_Revenue":1050,"Last_6M_Profit": 150}"}
P2 R1 {"3_MONTHS":"{"Last_3M_Cost":500,"Last_3M_Revenue":600,"Last_3M_Profit":100}","6_MONTHS":"{"Last_6M_Cost":1100,"Last_6M_Revenue":1400,"Last_6M_Profit": 300}"}
python dataframe apache-spark pyspark
© www.soinside.com 2019 - 2024. All rights reserved.