Justin Solms
Justin Solms

Reputation: 753

Pandas DataFrame Multiindex reindex columns not working

I have a DataFrame with a MultiIndex fopr the columns.

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

I wish to reindex thereby adding and 'Income' column.

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

No 'Income' column is added.

I also tried naming the level:

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

Upvotes: 2

Views: 1317

Answers (1)

jezrael
jezrael

Reputation: 863801

You need reindex by all columns - so need export MultiIndex to tuples, add value and last reindex:

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

Another posible solution is:

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

Upvotes: 2

Related Questions