2 回答

TA贡献1858条经验 获得超8个赞
pandas对索引使用唯一值。您设置了一个三重索引,如果这样做,似乎某些观测值将具有相同的三个值。结果,正在引发错误。pandas
我可以重现您的错误,更改示例的一个值,使其具有相同的索引值:
import pandas as pd
df = pd.read_clipboard()
df.iloc[2, 1] = 1
观测值 0 和 2 现在具有相同的(未来)索引值,这将引发错误。
ID ID_ver type count price discount
0 1 1 a 4 100 20 # 1, 1, a
1 1 1 b 3 50 0
2 1 1 a 4 100 30 # 1, 1, a
3 1 2 b 3 50 5
4 1 2 c 1 70 10
df.set_index(['ID','ID_ver','type'])[['count','price','discount']].unstack()
值错误:索引包含重复条目,无法改变形状

TA贡献1805条经验 获得超10个赞
我想你想要这样的东西:
pd.pivot_table(your_df, values=['count', 'price', 'discount'], index=['ID','ID_ver'], columns='type')
如果要从多索引列平展:
your_df.columns = ['_'.join(col).strip() for col in your_df.columns.values]
要平展行多索引:
your_df = your_df.reset_index()
编辑:更改为pivot_table,添加列拼合,行拼合
添加回答
举报