我有一个带有非唯一索引的 pandas DataFrame:
index = [1,1,1,1,2,2,2,3]
df = pd.DataFrame(data = {'col1': [1,3,7,6,2,4,3,4]}, index=index)
df
Out[12]:
col1
1 1
1 3
1 7
1 6
2 2
2 4
2 3
3 4
我想把它变成唯一的 MultiIndex 并保持顺序,就像这样:
col1
Ind2
1 0 1
1 3
2 7
3 6
2 0 2
1 4
2 3
3 0 4
我想 pandas 会有这样的功能,但还没有找到任何东西
最佳答案
你可以做一个groupby.cumcount
在索引上,然后使用 set_index
将其作为新级别附加到索引:
df = df.set_index(df.groupby(level=0).cumcount(), append=True)
结果输出:
col1
1 0 1
1 3
2 7
3 6
2 0 2
1 4
2 3
3 0 4
关于python - 从非唯一索引 Python Pandas 创建唯一的 MultiIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398251/