Python:多列枢轴和级别交换

2024-04-19 21:38:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个初始数据帧,格式如下:

store_id,product,sale_ind,total_sold,percentage_sold
1,thing1,sale,30,46.2
1,thing2,no_sale,20,30.7
1,thing3,sale,15,23.1
2,thing4,sale,10,16.7
2,thing3,sale,20,33.3
2,thing2,sale,30,50.0
3,thing3,no_sale,20,50.0
3,thing2,sale,15,37.5
3,thing1,no_sale,5,12.5

我已经计算了所有我想要的数据,但现在我真的很难将这些数据重塑为以下格式:

                product
                sale_in
         total_sold percentage_sold
store_id
1,
2,
3,

当我尝试这个:

df.pivot(index='store_id', columns='product')

我得到:ValueError: Index contains duplicate entries, cannot reshape。你知道吗

任何提示,非常感谢!我担心我可能不得不用层次索引来解决这个问题。你知道吗


Tags: 数据storenoid格式saleproducttotal
1条回答
网友
1楼 · 发布于 2024-04-19 21:38:04

多列透视需要pivot_table

df.pivot_table(
    index=['store_id'], 
    columns=['product', 'sale_ind'], 
    values=['total_sold', 'percentage_sold']
)

enter image description here

或者在您的情况下,数据透视时不涉及聚合,您可以使用set_indexunstack

df.set_index(['store_id', 'product', 'sale_ind']).unstack(['product', 'sale_ind'])

相关问题 更多 >