Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将列为月、行为年的数据框排序为单个时间序列?_Python_Pandas_Time Series - Fatal编程技术网

Python 如何将列为月、行为年的数据框排序为单个时间序列?

Python 如何将列为月、行为年的数据框排序为单个时间序列?,python,pandas,time-series,Python,Pandas,Time Series,我有一个数据框架,其中行是1880年到2014年的年份,列是1月到12月的月度数据。如何对数据进行排序,以获得单个时间序列?i、 e 1880-1 23 1880-2 66 等等 谢谢 最初,我的数据帧如下所示: jan, feb, mar, apl 1880 23 66... 首先要做的是将一月、二月、三月、十二月转换为1、2、3、12 现在您可以使用: 注意:在以后的分析中,您可能更喜欢使用多索引而不是多索引 In [21]:

我有一个数据框架,其中行是1880年到2014年的年份,列是1月到12月的月度数据。如何对数据进行排序,以获得单个时间序列?i、 e

    1880-1 23
    1880-2 66
等等

谢谢

最初,我的数据帧如下所示:

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

首先要做的是将一月、二月、三月、十二月转换为1、2、3、12

现在您可以使用:

注意:在以后的分析中,您可能更喜欢使用多索引而不是多索引

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

上面的答案对我有用,谢谢。有两点需要注意:

输入错误:month=a.index.get\u level\u values 1.values

应为:月=s.index.get\u level\u值1.values


另外,我的parse_dates=True,所以我的年份被读取为日期,然后PeriodIndex就不起作用了。当我忘了这一点时,一切都很好

到目前为止你尝试了什么?告诉我们,这不是一个代码生成的地方。这就是问题所在。我做了这么多,不知道该怎么办。我的意思是,我可以走C++的方式,遍历数据文件的元素,并将其存储并添加到列表中。我只是想知道是否有一种更优雅的肾盂疗法可以做到这一点。我甚至尝试按数据集进行折叠,但没有任何效果。
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
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