重新排列pandas数据透视表中的列

时间:2014-03-06 19:26:17

标签: python pandas

我有一个使用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)

我尝试使用以下两种方法以新订单重新排序'花费'和'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']]

1 个答案:

答案 0 :(得分:3)

一种方法是创建MultiIndex并重新索引:

In [11]: mi = pd.MultiIndex.from_product([['Imps', 'Spend'], ['3day avg','10day avg','30day avg','All']])

In [12]: df.reindex_axis(mi, 1)
Out[12]: 
               Imps                                        Spend                          
           3day avg   10day avg   30day avg         All 3day avg 10day avg 30day avg   All
All       8,029,438  17,617,872  17,302,111  14,156,666     $209      $439      $468  $368
Crossnet        116         NaN         110         113       $0       NaN        $0    $0
N/A       8,430,904  17,617,872  18,212,742  14,644,823     $219      $439      $492  $381

注意:MultiIndex.from_product是0.13中的新功能,如果您使用的是比此更早的pandas使用pd.MultiIndex.from_tuples(list(itertools.product(..)))