Pivot:大多数列作为索引

时间:2015-03-05 20:16:27

标签: python pandas

我有以下df:

    Jan 2004   Feb 2004   Mar 2004   Apr 2004   May 2004   Jun 2004  \
0        6.4        6.1        5.9        5.2        5.4        6.1   
1   134673.0   130294.0   126006.0   111309.0   114147.0   131745.0   
2  1985886.0  1990082.0  1999936.0  2009556.0  2009573.0  2013057.0   
3  2120559.0  2120376.0  2125942.0  2120865.0  2123720.0  2144802.0   
4        8.8        8.9        8.5        7.8        7.4        7.6   

    Jul 2004   Aug 2004   Sep 2004   Oct 2004     ...        May 2014  \
0        6.0        5.9        5.6        5.5     ...             6.6   
1   128010.0   126954.0   119043.0   119278.0     ...        142417.0   
2  2019963.0  2015320.0  2015103.0  2035705.0     ...       2009815.0   
3  2147973.0  2142274.0  2134146.0  2154983.0     ...       2152232.0   
4        6.5        6.2        6.5        6.8     ...             6.8   

    Jun 2014   Jul 2014   Aug 2014   Sep 2014   Oct 2014   Nov 2014  \
0        7.4        7.6        7.2        6.2        6.0        5.7   
1   161376.0   165248.0   154786.0   132918.0   128711.0   122831.0   
2  2008339.0  2003562.0  1994433.0  2001023.0  2019314.0  2016260.0   
3  2169715.0  2168810.0  2149219.0  2133941.0  2148025.0  2139091.0   
4        7.0        6.3        6.0        6.2        6.2        6.4   

    Dec 2014  state  type_string  
0        5.5     01          foo  
1   117466.0     01         barb  
2  2005276.0     01          asd  
3  2122742.0     01    foobarbar  
4        6.4     02          foo  

也就是说,我在每个美国州都有一组变量(foobarbasdfoobarbarfoo),如type_string

我想将数据框切换到一个结构,其中不同的日期(当前在列中)成为MultiIndex的较低级别,state成为MultiIndex的上一级。

我试过

datesIndex = df.columns[:-2]
stateIndex = pd.Index(df.state)
mindex = pd.MultiIndex.from_tuples((datesIndex, stateIndex))
df.pivot(index=mindex, columns='type_string')

但得到了

ValueError: Length mismatch: Expected axis has 208 elements, new values have 2 elements

我该如何处理?

预期产出

                      foo     barb      asd  foobarbar
      date  state
2004/01/01      1     6.4 134673.0  1985886    2120559
2004/02/01      1     6.1 130294.0  1990082    2120376
2004/03/01      1     5.9 126006.0  1999936    2125942

1 个答案:

答案 0 :(得分:2)

这可以通过pivot/transpose

来完成
In [195]: result = df.pivot(index='type_string', columns='state').T

In [196]: result.columns.name = None

In [197]: result
Out[197]: 
                    asd    barb  foo  foobarbar
         state                                 
Jan 2004 1      1985886  134673  6.4    2120559
         2          NaN     NaN  8.8        NaN
Feb 2004 1      1990082  130294  6.1    2120376
         2          NaN     NaN  8.9        NaN

这里的想法是columns='state'state列移动到日期旁边的列级别。因此,使用.T进行转置会转换索引和列,从而产生所需的结果。

相关问题