gpt4 book ai didi

python-3.x - 如何在多列中使用 pd.melt()?

转载 作者:行者123 更新时间:2023-12-03 09:40:12 25 4
gpt4 key购买 nike

我目前在创建名为 payment_types_Owned 的维度表时遇到问题列出客户拥有的产品数量、余额以及每次付款的限额。目前,我有一个看起来像这样的表:

cust_id 支付类型 X 拥有 支付类型 Y 拥有 支付类型 Z 拥有 已用信用_X 限制_X 已用信用_Y 限制_Y 已用信用_Z 限制_Z
0 人_A 1 3 4 300 700 700 800 400 900
1 人_B 2 1 3 400 600 100 150 400 500
2 人_C 2 4 4 500 600 700 800 100 500

我想要的输出:

cust_id 变量值 Credit Used Limit
0 Person_A_key 付款类型 X 1 300 700
1 Person_A_key 付款类型 Y 3 700 800
2 Person_A_key 付款类型 Z 4 400 900
3 Person_B_key 支付类型 X 2 400 600
4 Person_B_key 付款类型 Y 1 100 150
5 Person_B_key 付款类型 Z 3 400 500

假设我已经有另外 2 个维度表可以捕获以下信息:

  • Customer Dimension Table - 包含 cust_id 主键
  • Product Dimension Table - 包含唯一的产品主键

  • 使用 pd.melt() ,我得到以下,但它只是部分解决我的问题:

    (pd.melt(df, id_vars=['cust_id'], value_vars=['付款类型 X 拥有','付款类型 Y 拥有','付款类型 Z 拥有'])).sort_values(by=['cust_id' ])

    cust_id 变量值
    0 人_A 付款类型 X 1
    3 Person_A 付款类型 Y 3
    6 Person_A 付款类型 Z 4
    1 人_B 付款类型 X 2
    4 Person_B 付款类型 Y 1
    7 Person_B 付款类型 Z 3
    2 Person_C 付款类型 X 2
    5 Person_C 付款类型 Y 4
    8 Person_C 付款类型 Z 4

    有什么建议?

    最佳答案

    使用 wide_to_long ,但首先必须使用 Series.str.replace 与第一组Payment Type列:

    df.columns = df.columns.str.replace(' owned', '').str.replace('Payment Type ', 'Payment Type_')
    print (df)
    cust_id Payment Type_X Payment Type_Y Payment Type_Z Credit Used_X \
    0 Person_A 1 3 4 300
    1 Person_B 2 1 3 400
    2 Person_C 2 4 4 500

    Limit_X Credit Used_Y Limit_Y Credit Used_Z Limit_Z
    0 700 700 800 400 900
    1 600 100 150 400 500
    2 600 700 800 100 500

    df1 = pd.wide_to_long(df, stubnames=['Payment Type','Credit Used', 'Limit'],
    i='cust_id',
    j='variable',
    sep='_',
    suffix='\w+').sort_index(level=0).reset_index()

    最后将字符串添加到 variable列并按字典重命名列:
    df1 = (df1.assign(variable='Payment Type ' + df1['variable'])
    .rename(columns={'Payment Type':'value'}))
    print(df1)
    cust_id variable value Credit Used Limit
    0 Person_A Payment Type X 1 300 700
    1 Person_A Payment Type Y 3 700 800
    2 Person_A Payment Type Z 4 400 900
    3 Person_B Payment Type X 2 400 600
    4 Person_B Payment Type Y 1 100 150
    5 Person_B Payment Type Z 3 400 500
    6 Person_C Payment Type X 2 500 600
    7 Person_C Payment Type Y 4 700 800
    8 Person_C Payment Type Z 4 100 500

    关于python-3.x - 如何在多列中使用 pd.melt()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58169347/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com