首页 > 解决方案 > 从索引值创建列

问题描述

假设我的数据形状如本例所示

idx = pd.MultiIndex.from_product([[1, 2, 3, 4, 5, 6], ['a', 'b', 'c']],
                                 names=['numbers', 'letters'])
col = ['Value']

df = pd.DataFrame(list(range(18)), idx, col)

print(df.unstack())

输出将是

            Value        
letters     a   b   c
numbers              
1           0   1   2
2           3   4   5
3           6   7   8
4           9  10  11
5          12  13  14
6          15  16  17

lettersandnumbers是索引,Value 是唯一的列

问题是如何将Valuecolumn 替换为名为 index 值的列letters

所以我想得到这样的输出

numbers     a   b   c         
1           0   1   2
2           3   4   5
3           6   7   8
4           9  10  11
5          12  13  14
6          15  16  17

其中abc是列,数字是唯一的索引。

感谢你的帮助。

标签: pythonpython-3.xpandas

解决方案


问题是由您使用unstackwith引起的DataFrame,而不是pd.Series

df.Value.unstack().rename_axis(None,1)
Out[151]: 
          a   b   c
numbers            
1         0   1   2
2         3   4   5
3         6   7   8
4         9  10  11
5        12  13  14
6        15  16  17

推荐阅读