【问题标题】:pandas pivot dataframe, but add unseen values熊猫数据框,但添加看不见的值
【发布时间】:2021-03-08 16:16:01
【问题描述】:

我有 2 个数据框:

purchases = pd.DataFrame([['Alice', 'sweeties', 4],
                      ['Bob', 'chocolate', 5],
                      ['Alice', 'chocolate', 3],
                      ['Claudia', 'juice', 2]],
                    columns=['client', 'item', 'quantity'])

goods = pd.DataFrame([['sweeties', 15],
                  ['chocolate', 7],
                  ['juice', 8],
                  ['lemons', 3]], columns=['good', 'price'])

我想在这张照片上用 cols 和 index 转换购买:

我的第一个想法是使用枢轴:

purchases.pivot(columns="item", values="quantity")

输出:

问题是:我还需要数据透视结果中的柠檬列,因为它存在于货物数据框中(仅填充了 None 值)。

我怎样才能做到这一点?

【问题讨论】:

    标签: python-3.x pandas pivot-table


    【解决方案1】:

    您可以与reindex链接:

    purchases.pivot(columns="item", values="quantity").reindex(goods['good'], axis=1)
    

    输出:

    good  sweeties  chocolate  juice  lemons
    0          4.0        NaN    NaN     NaN
    1          NaN        5.0    NaN     NaN
    2          NaN        3.0    NaN     NaN
    3          NaN        NaN    2.0     NaN
    

    【讨论】:

    • 解决问题的好方法,谢谢
    【解决方案2】:

    您可以将df.mergedf.pivot 一起使用:

    In [3626]: x = goods.merge(purchases, left_on='good', right_on='item', how='left')
    In [3628]: x['total'] = x.price * x.quantity # you can tweak this calculation
    
    In [3634]: res = x[['good', 'client', 'total']].pivot('client', 'good', 'total').dropna(how='all').fillna(0)
    
    In [3635]: res
    Out[3635]: 
    good     chocolate  juice  lemons  sweeties
    client                                     
    Alice         21.0    0.0     0.0      60.0
    Bob           35.0    0.0     0.0       0.0
    Claudia        0.0   16.0     0.0       0.0
    

    【讨论】:

    • @АрсенийПроценко 如果答案对您有用,请告诉我。
    • 感谢您的回复,似乎在这个例子中有效,没有测试其他数据(因为缺少它们)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-08-08
    • 2021-06-11
    相关资源
    最近更新 更多