防止在pandas python中对列名进行排序

2024-03-28 13:00:48 发布

您现在位置:Python中文网/ 问答频道 /正文

df = pd.DataFrame(data={'i1':['x','x','x','x','y','y','y','y'], 'i2':['f','a','w','h','f','a','w','h'], 'c1':np.random.randn(8),'c2':np.random.randn(8)})
df.set_index(['i1','i2'],inplace=True)

df.unstack('i2')按字母顺序对i2中的列名进行排序。如何防止这种排序并保持原始序列(f a w h)?在


Tags: dataframedfdataindex排序nprandompd
2条回答

您可以使用ordered Categorical

df['i2'] = pd.Categorical(df.i2, categories=['f', 'a', 'w', 'h'], ordered=True)

df.set_index(['i1','i2'],inplace=True)
print (df)

print (df.unstack('i2'))
          c1                                      c2                      \
i2         f         a         w         h         f         a         w   
i1                                                                         
x  -0.663218  1.005395  0.236088  1.416896  2.729855  0.141692  0.136700   
y   0.509393  0.370418 -1.301840 -1.067212  0.945016 -0.617570  1.377235   


i2         h  
i1            
x  -0.029020  
y  -2.346038  

另一种方法是使用原始的index顺序对列进行set_levels

In [261]:
cols = df.columns
df1 = df.unstack('i2')
df1.columns = cols.set_levels(df.index.get_level_values(1), level=1)
df1

Out[261]:
          c1                                      c2                      \
i2         f         a         w         h         f         a         w   
i1                                                                         
x  -1.386403 -0.566924  0.007553 -0.189557 -1.108989  0.114203 -1.198163   
y   1.211754  1.270087  0.438575 -0.546983  1.943406  0.757389  0.286259   


i2         h  
i1            
x  -0.505088  
y  -0.629366  

相关问题 更多 >