首页 > 解决方案 > pandas 多行到单行,2 个索引上有多列

问题描述

我正在尝试从以下位置转换熊猫数据框:

ID ID_ver type count price discount
1  1      a    4     100   20
1  1      b    3     50    0
1  2      a    4     100   30
1  2      b    3     50    5
1  2      c    1     70    10

至:

ID ID_ver count_a price_a discount_a count_b price_b discount_b count_c price_c discount_c

我有 10 种不同的可能类型和数千个 ID,每个版本最多 10 个。

我试过了:

df.drop_duplicates()
df.set_index(['ID','ID_VER','TYPE'])[['count','PRICE','DISCOUNT']].unstack()

但得到错误:

索引包含重复条目,无法重塑。

尽我所能,不明白为什么。

谢谢你的帮助!

标签: pythonpandas

解决方案


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()

ValueError:索引包含重复的条目,无法重塑


推荐阅读