【问题标题】:Pandas DataFrame Multiindex reindex columns not workingPandas DataFrame Multiindex 重新索引列不起作用
【发布时间】:2017-03-02 09:54:42
【问题描述】:

我有一个带有 MultiIndex 列的 DataFrame。

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

我希望重新索引,从而添加“收入”列。

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

未添加“收入”列。

我也试过命名关卡:

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

【问题讨论】:

  • 答案不够好,无法接受??

标签: python pandas dataframe reindex


【解决方案1】:

所有列都需要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

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 1970-01-01
    • 2020-03-29
    • 2020-04-12
    • 2013-08-21
    • 1970-01-01
    • 2012-10-09
    • 2012-10-02
    • 1970-01-01
    相关资源
    最近更新 更多