Pandas DataFrame Multiindex 重新索引列不工作

Pandas DataFrame Multiindex reindex columns not working

我有一个 DataFrame,其中包含列的 MultiIndex。

ipdb> actions
flow                    inflow  outflow                   
action              Investment    Trade ExternalFee    Fee
date       sequence                                       
2016-10-18 50          15000.0      NaN         NaN    NaN
           55              NaN      NaN      -513.0    NaN
           60              NaN -14402.4         NaN    NaN
           70              NaN      NaN         NaN -14.29

我希望重新索引从而添加 'Income' 列。

ipdb> actions.reindex(columns=['Investment', 'Trade', 'ExternalFee', 'Fee', 'Income'], level=1)
flow                    inflow  outflow                   
action              Investment    Trade ExternalFee    Fee
date       sequence                                       
2016-10-18 50          15000.0      NaN         NaN    NaN
           55              NaN      NaN      -513.0    NaN
           60              NaN -14402.4         NaN    NaN
           70              NaN      NaN         NaN -14.29

未添加 'Income' 列。

我也试过命名关卡:

ipdb> actions.reindex(columns=['Investment', 'Trade', 'Income'], level='action')
flow                    inflow  outflow
action              Investment    Trade
date       sequence                    
2016-10-18 50          15000.0      NaN
           55              NaN      NaN
           60              NaN -14402.4

所有列都需要 reindex - 所以需要导出 MultiIndex 到元组,添加值并最后重新索引:

tuples = actions.columns.tolist()
tuples = tuples + [('outflow','Income')]
print (tuples)
[('inflow', 'Investment'), ('outflow', 'Trade'), 
 ('outflow', 'ExternalFee'), ('outflow', 'Fee'), 
('outflow', 'Income')]

a = actions.reindex(columns=pd.MultiIndex.from_tuples(tuples))
print (a)
                  inflow  outflow                          
              Investment    Trade ExternalFee    Fee Income
2016-10-18 50    15000.0      NaN         NaN    NaN    NaN
           55        NaN      NaN      -513.0    NaN    NaN
           60        NaN -14402.4         NaN    NaN    NaN
           70        NaN      NaN         NaN -14.29    NaN

另一种可能的解决方案是:

actions[('outflow','Income')] = np.nan
print (actions)
action            inflow  outflow                          
date          Investment    Trade ExternalFee    Fee Income
2016-10-18 50    15000.0      NaN         NaN    NaN    NaN
           55        NaN      NaN      -513.0    NaN    NaN
           60        NaN -14402.4         NaN    NaN    NaN
           70        NaN      NaN         NaN -14.29    NaN