如何对列为月份的数据框和单个时间序列中的行进行排序?

时间:2014-12-21 04:57:23

标签: python pandas time-series

我有一个数据框,其中行是从1880年到2014年的年份,列是从1月到12月的月度数据。我如何对数据进行排序,以便我有一个时间序列?即

    1880-1 23
    1880-2 66

等...

感谢

最初,我的数据框看起来像这样:

            jan, feb, mar, apl
    1880    23    66...

1 个答案:

答案 0 :(得分:1)

首先要做的是将jan, feb, mar, ..., dec转换为1, 2, 3, ..., 12

df.columns = range(1, 13)

现在您可以使用stack

In [11]: df = pd.DataFrame([[23, 66, 42], [11, 14, 15]], index=[1880, 1881], columns=[1, 2, 3])

In [12]: df
Out[12]:
       1   2   3
1880  23  66  42
1881  11  14  15

In [13]: df.stack()
Out[13]:
1880  1    23
      2    66
      3    42
1881  1    11
      2    14
      3    15
dtype: int64

注意:您可能更喜欢PeriodIndex(而不是MultiIndex)以供日后分析。

In [21]: s = df.stack()
         year = s.index.get_level_values(0).values
         month = a.index.get_level_values(1).values

In [22]: pd.PeriodIndex(year=year, month=month, freq='M')
Out[22]:
<class 'pandas.tseries.period.PeriodIndex'>
[1880-01, ..., 1881-03]
Length: 6, Freq: M

In [23]: s.index = pd.PeriodIndex(year=year, month=month, freq='M')

In [24]: s
Out[24]:
1880-01    23
1880-02    66
1880-03    42
1881-01    11
1881-02    14
1881-03    15
Freq: M, dtype: int64