我正在寻找一种在熊猫中添加更高级别列索引的方法。
我有一个这样的多索引熊猫数据框:
>>>df
product A B C
sell_buy sell buy sell buy sell buy
group company
1 Bank X 100 50 200 10 20 20
2 Bank Y 20 40 150 40 30 20
3 Bank Z 100 20 20 10 40 10
我想在company
的列中添加更高级别的索引,并用今天的日期设置行索引(使用类似datetime.today()
的内容)
company Bank X Bank Y Bank Z
product A B C A B C A B C
sell_buy sell buy sell buy sell buy sell buy sell buy sell buy sell buy sell buy sell buy
2020-08-15 100 50 200 10 20 20 20 40 150 40 30 20 100 20 20 10 40 10
我尝试了几次尝试,但是我不知道如何使它工作...
pd.MultiIndex.from_product([df.columns.levels, ['Bank X']])
pd.MultiIndex.from_product([df.columns.levels, ['product']])
任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
我相信您首先需要将第一级转换为date
值,然后通过DataFrame.unstack
,MultiIndex.reorder_levels
和DataFrame.sort_index
进行整形:
date = pd.Timestamp('today').floor('d')
df.index = pd.MultiIndex.from_product([[date], df.index.get_level_values(1)])
df = df.unstack().reorder_levels([2,0,1], axis=1).sort_index(axis=1)
print (df)
company Bank X Bank Y Bank Z \
product A B C A B C A
sell_buy buy sell buy sell buy sell buy sell buy sell buy sell buy
2020-08-15 50 100 10 200 20 20 40 20 40 150 20 30 20
company
product B C
sell_buy sell buy sell buy sell
2020-08-15 100 10 20 10 40