[英]Not able to remove MultiIndex in pandas dataframe
我是具有以下結構的數據框df
。 我試圖`df.reset_index()刪除multiIndex。 但是它不起作用。
df.reindex_axis(sorted(df.columns), axis=1)
print(df.columns)
MultiIndex(levels=[['MID Index', 'RLG Index', 'RLV Index', 'RTY Index', 'S5COND Index', 'S5CONS Index', 'S5ENRS Index', 'S5FINL Index', 'S5HLTH Index', 'S5INDU Index', 'S5INFT Index', 'S5MATR Index', 'S5RLST Index', 'S5TELS Index', 'S5UTIL Index', 'SPX Index', 'date'], ['LP', 'PX', '']],
labels=[[16, 7, 7, 15, 15, 0, 0, 8, 8, 3, 3, 9, 9, 2, 2, 10, 10, 1, 1, 11, 11, 12, 12, 4, 4, 13, 13, 5, 5, 14, 14, 6, 6], [2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]],
names=['ticker', 'field'])
如果無法刪除multiIndex,則至少需要根據列名對列進行重新排序。 我嘗試了上述代碼進行重新排序,但無法正常工作。 誰能幫幫我嗎
附加輸入數據框文件df
打印(DF)
Out[35]:
user_id a s
session b b C b C
revenue -1 0 1 2 1
OP1
df.columns=df.columns.map('_'.join)
df
Out[37]:
a_b a_b s_C s_b s_C
revenue -1 0 1 2 1
OP2
df.T.reset_index()
Out[41]:
user_id session revenue
0 a b -1
1 a b 0
2 s C 1
3 s b 2
4 s C 1
然后進行以下計算
數據輸入:
df = pd.DataFrame({'user_id':['a','a','s','s','s'],
'session':['b','b','C','b','C'],
'revenue':[-1,0,1,2,1]})
df=df.set_index(['user_id','session']).T
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.