8.3 重塑和轴向旋转

    层次化索引为DataFrame数据的重排任务提供了一种具有良好一致性的方式。主要功能有二:

    • stack:将数据的列“旋转”为行。
    • unstack:将数据的行“旋转”为列。

    我将通过一系列的范例来讲解这些操作。接下来看一个简单的DataFrame,其中的行列索引均为字符串数组:

    对该数据使用stack方法即可将列转换为行,得到一个Series:

    1. In [123]: result
    2. Out[123]:
    3. state number
    4. Ohio one 0
    5. two 1
    6. three 2
    7. Colorado one 3
    8. two 4
    9. three 5
    10. dtype: int64

    对于一个层次化索引的Series,你可以用unstack将其重排为一个DataFrame:

    1. In [124]: result.unstack()
    2. Out[124]:
    3. number one two three
    4. state
    5. Ohio 0 1 2
    6. Colorado 3 4 5

    默认情况下,unstack操作的是最内层(stack也是如此)。传入分层级别的编号或名称即可对其它级别进行unstack操作:

    1. In [125]: result.unstack(0)
    2. Out[125]:
    3. state Ohio Colorado
    4. number
    5. one 0 3
    6. two 1 4
    7. three 2 5
    8. In [126]: result.unstack('state')
    9. Out[126]:
    10. state Ohio Colorado
    11. number
    12. one 0 3
    13. two 1 4
    14. three 2 5

    如果不是所有的级别值都能在各分组中找到的话,则unstack操作可能会引入缺失数据:

    1. In [127]: s1 = pd.Series([0, 1, 2, 3], index=['a', 'b', 'c', 'd'])
    2. In [128]: s2 = pd.Series([4, 5, 6], index=['c', 'd', 'e'])
    3. In [129]: data2 = pd.concat([s1, s2], keys=['one', 'two'])
    4. In [130]: data2
    5. Out[130]:
    6. one a 0
    7. b 1
    8. c 2
    9. d 3
    10. two c 4
    11. d 5
    12. e 6
    13. dtype: int64
    14. In [131]: data2.unstack()
    15. Out[131]:
    16. a b c d e
    17. one 0.0 1.0 2.0 3.0 NaN
    18. two NaN NaN 4.0 5.0 6.0
    1. In [132]: data2.unstack()
    2. Out[132]:
    3. a b c d e
    4. one 0.0 1.0 2.0 3.0 NaN
    5. two NaN NaN 4.0 5.0 6.0
    6. In [133]: data2.unstack().stack()
    7. Out[133]:
    8. one a 0.0
    9. b 1.0
    10. c 2.0
    11. d 3.0
    12. two c 4.0
    13. d 5.0
    14. e 6.0
    15. dtype: float64
    16. In [134]: data2.unstack().stack(dropna=False)
    17. Out[134]:
    18. b 1.0
    19. c 2.0
    20. d 3.0
    21. two a NaN
    22. b NaN
    23. c 4.0
    24. d 5.0
    25. e 6.0
    26. dtype: float64

    在对DataFrame进行unstack操作时,作为旋转轴的级别将会成为结果中的最低级别:

    当调用stack,我们可以指明轴的名字:

    1. In [138]: df.unstack('state').stack('side')
    2. Out[138]:
    3. state Colorado Ohio
    4. number side
    5. one left 3 0
    6. right 8 5
    7. two left 4 1
    8. right 9 6
    9. three left 5 2
    10. right 10 7

    多个时间序列数据通常是以所谓的“长格式”(long)或“堆叠格式”(stacked)存储在数据库和CSV中的。我们先加载一些示例数据,做一些时间序列规整和数据清洗:

    1. In [139]: data = pd.read_csv('examples/macrodata.csv')
    2. In [140]: data.head()
    3. Out[140]:
    4. year quarter realgdp realcons realinv realgovt realdpi cpi \
    5. 0 1959.0 1.0 2710.349 1707.4 286.898 470.045 1886.9 28.98
    6. 1 1959.0 2.0 2778.801 1733.7 310.859 481.301 1919.7 29.15
    7. 2 1959.0 3.0 2775.488 1751.8 289.226 491.260 1916.4 29.35
    8. 3 1959.0 4.0 2785.204 1753.7 299.356 484.052 1931.3 29.37
    9. 4 1960.0 1.0 2847.699 1770.5 331.722 462.199 1955.5 29.54
    10. m1 tbilrate unemp pop infl realint
    11. 0 139.7 2.82 5.8 177.146 0.00 0.00
    12. 1 141.7 3.08 5.1 177.830 2.34 0.74
    13. 2 140.5 3.82 5.3 178.657 2.74 1.09
    14. 3 140.0 4.33 5.6 179.386 0.27 4.06
    15. 4 139.6 3.50 5.2 180.007 2.31 1.19
    16. In [141]: periods = pd.PeriodIndex(year=data.year, quarter=data.quarter,
    17. .....: name='date')
    18. In [142]: columns = pd.Index(['realgdp', 'infl', 'unemp'], name='item')
    19. In [143]: data = data.reindex(columns=columns)
    20. In [144]: data.index = periods.to_timestamp('D', 'end')
    21. In [145]: ldata = data.stack().reset_index().rename(columns={0: 'value'})

    这就是多个时间序列(或者其它带有两个或多个键的可观察数据,这里,我们的键是date和item)的长格式。表中的每行代表一次观察。

    关系型数据库(如MySQL)中的数据经常都是这样存储的,因为固定架构(即列名和数据类型)有一个好处:随着表中数据的添加,item列中的值的种类能够增加。在前面的例子中,date和item通常就是主键(用关系型数据库的说法),不仅提供了关系完整性,而且提供了更为简单的查询支持。有的情况下,使用这样的数据会很麻烦,你可能会更喜欢DataFrame,不同的item值分别形成一列,date列中的时间戳则用作索引。DataFrame的pivot方法完全可以实现这个转换:

    1. In [147]: pivoted = ldata.pivot('date', 'item', 'value')
    2. In [148]: pivoted
    3. Out[148]:
    4. item infl realgdp unemp
    5. date
    6. 1959-03-31 0.00 2710.349 5.8
    7. 1959-06-30 2.34 2778.801 5.1
    8. 1959-09-30 2.74 2775.488 5.3
    9. 1959-12-31 0.27 2785.204 5.6
    10. 1960-03-31 2.31 2847.699 5.2
    11. 1960-06-30 0.14 2834.390 5.2
    12. 1960-09-30 2.70 2839.022 5.6
    13. 1960-12-31 1.21 2802.616 6.3
    14. 1961-03-31 -0.40 2819.264 6.8
    15. 1961-06-30 1.47 2872.005 7.0
    16. ... ... ... ...
    17. 2007-06-30 2.75 13203.977 4.5
    18. 2007-09-30 3.45 13321.109 4.7
    19. 2007-12-31 6.38 13391.249 4.8
    20. 2008-03-31 2.82 13366.865 4.9
    21. 2008-06-30 8.53 13415.266 5.4
    22. 2008-09-30 -3.16 13324.600 6.0
    23. 2008-12-31 -8.79 13141.920 6.9
    24. 2009-03-31 0.94 12925.410 8.1
    25. 2009-06-30 3.37 12901.504 9.2
    26. 2009-09-30 3.56 12990.341 9.6
    27. [203 rows x 3 columns]

    前两个传递的值分别用作行和列索引,最后一个可选值则是用于填充DataFrame的数据列。假设有两个需要同时重塑的数据列:

    1. In [149]: ldata['value2'] = np.random.randn(len(ldata))
    2. In [150]: ldata[:10]
    3. Out[150]:
    4. 0 1959-03-31 realgdp 2710.349 0.523772
    5. 2 1959-03-31 unemp 5.800 1.343810
    6. 3 1959-06-30 realgdp 2778.801 -0.713544
    7. 4 1959-06-30 infl 2.340 -0.831154
    8. 5 1959-06-30 unemp 5.100 -2.370232
    9. 6 1959-09-30 realgdp 2775.488 -1.860761
    10. 7 1959-09-30 infl 2.740 -0.860757
    11. 8 1959-09-30 unemp 5.300 0.560145
    12. 9 1959-12-31 realgdp 2785.204 -1.265934
    1. In [151]: pivoted = ldata.pivot('date', 'item')
    2. In [152]: pivoted[:5]
    3. Out[152]:
    4. value value2
    5. item infl realgdp unemp infl realgdp unemp
    6. date
    7. 1959-03-31 0.00 2710.349 5.8 0.000940 0.523772 1.343810
    8. 1959-06-30 2.34 2778.801 5.1 -0.831154 -0.713544 -2.370232
    9. 1959-09-30 2.74 2775.488 5.3 -0.860757 -1.860761 0.560145
    10. 1959-12-31 0.27 2785.204 5.6 0.119827 -1.265934 -1.063512
    11. 1960-03-31 2.31 2847.699 5.2 -2.359419 0.332883 -0.199543
    12. In [153]: pivoted['value'][:5]
    13. Out[153]:
    14. item infl realgdp unemp
    15. date
    16. 1959-03-31 0.00 2710.349 5.8
    17. 1959-06-30 2.34 2778.801 5.1
    18. 1959-09-30 2.74 2775.488 5.3
    19. 1959-12-31 0.27 2785.204 5.6
    20. 1960-03-31 2.31 2847.699 5.2

    注意,pivot其实就是用set_index创建层次化索引,再用unstack重塑:

    旋转DataFrame的逆运算是pandas.melt。它不是将一列转换到多个新的DataFrame,而是合并多个列成为一个,产生一个比输入长的DataFrame。看一个例子:

    1. In [157]: df = pd.DataFrame({'key': ['foo', 'bar', 'baz'],
    2. .....: 'A': [1, 2, 3],
    3. .....: 'B': [4, 5, 6],
    4. .....: 'C': [7, 8, 9]})
    5. In [158]: df
    6. Out[158]:
    7. A B C key
    8. 0 1 4 7 foo
    9. 1 2 5 8 bar
    10. 2 3 6 9 baz

    key列可能是分组指标,其它的列是数据值。当使用pandas.melt,我们必须指明哪些列是分组指标。下面使用key作为唯一的分组指标:

    1. In [159]: melted = pd.melt(df, ['key'])
    2. In [160]: melted
    3. Out[160]:
    4. key variable value
    5. 0 foo A 1
    6. 1 bar A 2
    7. 2 baz A 3
    8. 3 foo B 4
    9. 4 bar B 5
    10. 5 baz B 6
    11. 6 foo C 7
    12. 7 bar C 8
    13. 8 baz C 9

    使用pivot,可以重塑回原来的样子:

    1. In [161]: reshaped = melted.pivot('key', 'variable', 'value')
    2. In [162]: reshaped
    3. Out[162]:
    4. variable A B C
    5. key
    6. bar 2 5 8
    7. baz 3 6 9
    8. foo 1 4 7

    因为pivot的结果从列创建了一个索引,用作行标签,我们可以使用reset_index将数据移回列:

    1. In [163]: reshaped.reset_index()
    2. Out[163]:
    3. variable key A B C
    4. 0 bar 2 5 8
    5. 1 baz 3 6 9
    6. 2 foo 1 4 7

    你还可以指定列的子集,作为值的列:

    1. In [164]: pd.melt(df, id_vars=['key'], value_vars=['A', 'B'])
    2. Out[164]:
    3. key variable value
    4. 0 foo A 1
    5. 1 bar A 2
    6. 2 baz A 3
    7. 3 foo B 4
    8. 5 baz B 6