Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.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_Dataframe - Fatal编程技术网

Python 按组重新编制熊猫时间序列索引

Python 按组重新编制熊猫时间序列索引,python,pandas,time-series,dataframe,Python,Pandas,Time Series,Dataframe,所以我要做的是重新索引一个数据帧,这个数据帧中有一组独立的组。每个都有自己的索引,我想在其中添加一个月末索引。我认为最好举个例子: 给定此数据帧: In [72]: a = {'2014-01-02': {'A': 1}, '2014-02-03': {'A': 1}, '2014-03-05': {'A': 1}} In [74]: b = {'2015-01-02': {'A': 2}, '2015-02-03': {'A': 2}, '2015-03-05': {'A': 2}} In

所以我要做的是重新索引一个数据帧,这个数据帧中有一组独立的组。每个都有自己的索引,我想在其中添加一个月末索引。我认为最好举个例子:

给定此数据帧:

In [72]: a = {'2014-01-02': {'A': 1}, '2014-02-03': {'A': 1}, '2014-03-05': {'A': 1}}

In [74]: b = {'2015-01-02': {'A': 2}, '2015-02-03': {'A': 2}, '2015-03-05': {'A': 2}}
In [76]: pd.DataFrame.from_dict(a,orient='index').append(pd.DataFrame.from_dict(b,orient='index'))
Out[76]:
            A
2014-01-02  1
2014-02-03  1
2014-03-05  1
2015-01-02  2
2015-02-03  2
2015-03-05  2
(注意2014年与2015年的对比)

我想将“A”列中的两个组重新编制索引,以包括每个组的月末,从最小值到索引最大值后的月末。我想要这样的输出:

            A
2014-01-02  1
2014-01-31  1
2014-02-03  1
2014-02-28  1
2014-03-05  1
2014-03-31  1
2015-01-02  2
2015-01-31  2
2015-02-03  2
2015-02-28  2
2015-03-05  2
2015-03-31  2

首先,为数据帧提供一个别名

df = pd.DataFrame.from_dict(a,orient='index').append(pd.DataFrame.from_dict(b,orient='index'))
接下来,将行名称重置为索引

df.reset_index(level=0, inplace=True)
现在,检查数据帧的索引

list(df.columns.values)

这现在是多索引的,因此“A”是一个索引,聚合函数将针对该附加索引级别进行操作

您需要在数据帧上使用“多索引”。查看pandas文档中的“多索引”将是一个很好的起点。我接受了这一点,但也遇到了一个问题。如果您在同一个月有两个,现在使用A的平均值。在这种情况下,有没有办法让它做两个条目,一个为1,一个为2?如果你在同一个月有两个条目,你说的
是什么意思?如果a==1在索引中有2015-02-04,a==2在索引中有2015-02-05
In [59]:
df.index = pd.to_datetime(df.index , format = '%Y-%m-%d')
df
Out[59]:
            A
2014-01-02  1
2014-02-03  1
2014-03-05  1
2015-01-02  2
2015-02-03  2
2015-03-05  2

In [61]:
month_end = df.resample('M').dropna()
month_end
Out[61]:
            A
2014-01-31  1
2014-02-28  1
2014-03-31  1
2015-01-31  2
2015-02-28  2
2015-03-31  2

In [64]:
pd.concat([df , month_end]).sortlevel(0)
Out[64]:
            A
2014-01-02  1
2014-01-31  1
2014-02-03  1
2014-02-28  1
2014-03-05  1
2014-03-31  1
2015-01-02  2
2015-01-31  2
2015-02-03  2
2015-02-28  2
2015-03-05  2
2015-03-31  2