我有一个使用pivot_table方法创建的pandas数据框。它的结构如下:
import numpy as np
import pandas
datadict = {
('Imps', '10day avg'): {'All': '17,617,872', 'Crossnet': np.nan, 'N/A': '17,617,872'},
('Imps', '30day avg'): {'All': '17,302,111', 'Crossnet': '110','N/A': '18,212,742'},
('Imps', '3day avg'): {'All': '8,029,438', 'Crossnet': '116', 'N/A': '8,430,904'},
('Imps', 'All'): {'All': '14,156,666', 'Crossnet': '113', 'N/A': '14,644,823'},
('Spend', '10day avg'): {'All': '$439', 'Crossnet': np.nan, 'N/A': '$439'},
('Spend', '30day avg'): {'All': '$468', 'Crossnet': '$0', 'N/A': '$492'},
('Spend', '3day avg'): {'All': '$209', 'Crossnet': '$0', 'N/A': '$219'},
('Spend', 'All'): {'All': '$368', 'Crossnet': '$0', 'N/A': '$381'}
}
df = pandas.DataFrame.from_dict(datadict)
df.columns = pandas.MultiIndex.from_tuples(df.columns)
我尝试使用以下两种方法重新排列"Spend"和"Imps"下的嵌套列,但是尽管没有出现错误,顺序仍然没有改变:
df['Spend']=df['Spend'].reindex_axis(['3day avg','10day avg','30day avg','All'],axis=1)
df['Spend']=df['Spend'][['3day avg','10day avg','30day avg','All']]