从多索引 pandas 系列创建 1 列数据框

Create 1-column dataframe from multi-index pandas series

我有一个像这样的多索引系列:

Year  Month
2012  1        444
      2        222
      3        333
      4        1101

我想变成:

Date      Value
2012-01   444
2012-02   222
2012-03   333
2012-04   1101

画一条线。

我已经尝试了 series.unstack(level=0)series.unstack(level=1),但这会创建一个矩阵

In[1]: series.unstack(level=0)
Out[1]: 
Year   2012  2013  2014  2015  2016  2017   2018
Month                                          
1      444  ...   ...   ...   ...   ...    ...
2      222  ...   ...   ...   ...   ...    ...
3      333  ...   ...   ...   ...   ...    ...
4      1101 ...   ...   ...   ...   ...    ...

我错过了什么?

如果还添加了 Day 列,则使用 Index.to_frame with to_datetime 工作,并返回:

s.index = pd.to_datetime(s.index.to_frame().assign(Day=1))
print (s)
2012-01-01     444
2012-02-01     222
2012-03-01     333
2012-04-01    1101
Name: a, dtype: int64

对于一列 DataFrame 使用 Series.to_frame:

df1 = s.to_frame('Value')
print (df1)
            Value
2012-01-01    444
2012-02-01    222
2012-03-01    333
2012-04-01   1101

如果需要 PeriodIndex 添加 Series.dt.to_period:

s.index = pd.to_datetime(s.index.to_frame().assign(Day=1)).dt.to_period('m')
print (s)
2012-01     444
2012-02     222
2012-03     333
2012-04    1101
Freq: M, Name: a, dtype: int64

df2 = s.to_frame('Value')
print (df2)
         Value
2012-01    444
2012-02    222
2012-03    333
2012-04   1101
idx = pd.PeriodIndex(
    year=s.index.get_level_values(0).tolist(), 
    month=s.index.get_level_values(1).tolist(), 
    freq='M', 
    name='Date'
)
s2 = pd.Series(s.values, index=idx, name=s.name)
s2.plot()

您还可以使用带有 f-strings 的列表理解来创建 DatetimeIndex。

idx = pd.to_datetime([f'{year}-{month}' for year, month in s.index])