Skip to main content
 首页 » 编程设计

python之从索引值创建列

2025年05月04日21freeliver54

假设我的数据按照这个例子进行整形

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 

letters 和numbers 是索引,Value 是唯一的列

问题是如何将 Value 列替换为以索引 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 

其中 a、b 和 c 是列,数字是唯一的索引。

感谢您的帮助。

请您参考如下方法:

问题是由于您使用 unstack 和 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