我将如何采取这样的 df:
Dates Type 1 2 3 ...
2018-01-01 Type1 Golf Van Jeep
2018-01-02 Type1 Golf Van Jeep
2018-01-01 Type2 Golf1 Van1 Jeep1
2018-01-02 Type2 Golf2 Van2 Jeep2
并将其变成:
Type1 Type2
Dates 1 2 3 1 2 3 ...
2018-01-01 Golf Van Jeep Golf1 Van1 Jeep1
2018-01-02 Golf Van Jeep Golf2 Van2 Jeep2
编辑: 我想引入第二个索引,如下所示:
Type Type1 Type2
Numbers 1 2 3 1 2 3
Dates ...
2018-01-01 Golf Van Jeep Golf1 Van1 Jeep1
2018-01-02 Golf Van Jeep Golf2 Van2 Jeep2
编辑: 现在,如果我想重新标记所有数字索引值 - 我将如何创建它:
Type Type1 Type2
Numbers p1 p2 p3 p1 p2 p3
Dates ...
2018-01-01 Golf Van Jeep Golf1 Van1 Jeep1
2018-01-02 Golf Van Jeep Golf2 Van2 Jeep2
编辑:
可以只使用:
.add_prefix('hh')
最佳答案
使用DataFrame.set_index
与 DataFrame.unstack
,然后按 DataFrame.swaplevel
更改级别顺序并按 DataFrame.sort_index
对 MultiIndex
进行排序:
df = df.set_index(['Dates','Type']).unstack().swaplevel(0,1, axis=1).sort_index(axis=1)
print (df)
Type Type1 Type2
1 2 3 1 2 3
Dates
2018-01-01 Golf Van Jeep Golf1 Van1 Jeep1
2018-01-02 Golf Van Jeep Golf2 Van2 Jeep2
编辑:添加DataFrame.rename_axis
按元组:
df = (df.set_index(['Dates','Type'])
.unstack()
.swaplevel(0,1, axis=1)
.sort_index(axis=1)
.rename_axis(('Type','Numbers'), axis=1))
print (df)
Type Type1 Type2
Numbers 1 2 3 1 2 3
Dates
2018-01-01 Golf Van Jeep Golf1 Van1 Jeep1
2018-01-02 Golf Van Jeep Golf2 Van2 Jeep2
关于python - 来自 Dataframe 的多索引 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60434713/