将多索引索引转换为列

时间:2014-01-15 20:43:58

标签: python-2.7 pandas pivot multi-index

我定义了一个多索引数据框,例如as:

import pandas as pd
import numpy as np

dates = pd.date_range('20130101',periods=3,freq='5s')
dates = dates.append(dates)

locations = list('AAABBB')
gascode = ['no2','o3','so2']*2

tup = pd.MultiIndex.from_tuples( zip(locations,gascode,dates), names=['Location','gas','Date'] )

data = pd.DataFrame(data=range(6),index=tup,columns=['val1'])

>>> data

Location gas Date                  val1         
A        no2 2013-01-01 00:00:00     0
         o3  2013-01-01 00:00:05     1
         so2 2013-01-01 00:00:10     2
B        no2 2013-01-01 00:00:00     3
         o3  2013-01-01 00:00:05     4
         so2 2013-01-01 00:00:10     5

仅从位置'A'保存数据:

data = data.xs(key='A',level='Location')

现在,我想根据'gas'索引创建新列以产生:

Date                   no2   o3   so2
2013-01-01 00:00:00     0    nan  nan
2013-01-01 00:00:05     nan  1    nan
2013-01-01 00:00:10     nan  nan  2

我试图绕过'date'索引将'gas'放到列中,尽管这失败了。

data = data.pivot(index=data.index.get_level_values(level='date'),
                  columns=situ.index.get_level_values(level='gas'))

我无法实现这一目标;任何人都可以推荐替代品?

1 个答案:

答案 0 :(得分:4)

您可以unstack结果:

In [11]: data.xs(key='A', level='Location').unstack(0)
Out[11]: 
                     val1         
gas                   no2  o3  so2
Date                              
2013-01-01 00:00:00     0 NaN  NaN
2013-01-01 00:00:05   NaN   1  NaN
2013-01-01 00:00:10   NaN NaN    2

[3 rows x 3 columns]