Python 熊猫:将列分组为时间序列

Python 熊猫:将列分组为时间序列,python,pandas,time-series,Python,Pandas,Time Series,考虑这组数据: data = [{'Year':'1959:01','0':138.89,'1':139.39,'2':139.74,'3':139.69,'4':140.68,'5':141.17}, {'Year':'1959:07','0':141.70,'1':141.90,'2':141.01,'3':140.47,'4':140.38,'5':139.95}, {'Year':'1960:01','0':139.98,'1':139.87,'2':13

考虑这组数据:

data = [{'Year':'1959:01','0':138.89,'1':139.39,'2':139.74,'3':139.69,'4':140.68,'5':141.17},
        {'Year':'1959:07','0':141.70,'1':141.90,'2':141.01,'3':140.47,'4':140.38,'5':139.95},
        {'Year':'1960:01','0':139.98,'1':139.87,'2':139.75,'3':139.56,'4':139.61,'5':139.58}]
如何转换为熊猫时间序列,如下所示:

Year    Value
1959-01 138.89  
1959-02 139.39  
1959-03 139.74
...
1959-07 141.70
1959-08 141.90
...
这里有一条路

s = pd.DataFrame(data).set_index("Year").stack()
s.index = pd.Index([pd.to_datetime(start, format="%Y:%m") + pd.DateOffset(months=int(off))
                    for start, off in s.index], name="Year")
df = s.to_frame("Value")
首先,我们将
Year
设置为索引,然后将其旁边的值堆叠起来。然后通过可用日期+其他值(作为月偏移量)从当前索引准备索引。最后转到新列名称为
Value
的框架

得到

>>> df

             Value
Year
1959-01-01  138.89
1959-02-01  139.39
1959-03-01  139.74
1959-04-01  139.69
1959-05-01  140.68
1959-06-01  141.17
1959-07-01  141.70
1959-08-01  141.90
1959-09-01  141.01
1959-10-01  140.47
1959-11-01  140.38
1959-12-01  139.95
1960-01-01  139.98
1960-02-01  139.87
1960-03-01  139.75
1960-04-01  139.56
1960-05-01  139.61
1960-06-01  139.58
代码

df = pd.DataFrame(data).set_index('Year').stack().droplevel(1)
df.index=pd.date_range(start=pd.to_datetime(df.index, format='%Y:%m')[0], 
                         periods=len(df.index), freq='M').to_period('M')                   
df = df.to_frame().reset_index().rename(columns={'index': 'Year', (0):'Value'})
解释

使用
堆栈
将df转换为
系列
,并删除不需要的
级别。
然后,
重置
所需范围的
索引
,因为我们需要每月频率的输出,因此使用
到周期
。 最后一步是将系列转换回框架并重命名列

根据需要输出

    Year    Value
0   1959-01 138.89
1   1959-02 139.39
2   1959-03 139.74
3   1959-04 139.69
4   1959-05 140.68
5   1959-06 141.17
6   1959-07 141.70
7   1959-08 141.90
8   1959-09 141.01
9   1959-10 140.47
10  1959-11 140.38
11  1959-12 139.95
12  1960-01 139.98
13  1960-02 139.87
14  1960-03 139.75
15  1960-04 139.56
16  1960-05 139.61
17  1960-06 139.58