[英]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
我希望重新索引,从而添加“收入”列。
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
您需要按所有列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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.