Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.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 将DateTimeIndex与年月合并_Python_Pandas - Fatal编程技术网

Python 将DateTimeIndex与年月合并

Python 将DateTimeIndex与年月合并,python,pandas,Python,Pandas,我有两个数据帧。一个是精确的(每日)DateTimeIndex。我使用该索引创建了使用groupby(['groupid',pd.TimeGrouper('1M',closed='left',label='left'))的月度统计数据。 现在我想将信息合并回原始数据帧。但是,折叠数据框的日期时间标签当然与原始的DateTimeIndex不完全对应。然后我想将它们与相应的月份和年份信息进行匹配 我该怎么做 statistics date

我有两个数据帧。一个是精确的(每日)
DateTimeIndex
。我使用该索引创建了使用
groupby(['groupid',pd.TimeGrouper('1M',closed='left',label='left'))的月度统计数据。

现在我想将信息合并回原始数据帧。但是,折叠数据框的日期时间标签当然与原始的
DateTimeIndex
不完全对应。然后我想将它们与相应的月份和年份信息进行匹配

我该怎么做

                         statistics 
  date          groupid            
  2001-01-31          1          10
  2001-02-31          1          11
和原始数据帧

  date          groupid         foo
  2001-01-25          1           1
  2001-01-28          1           2
  2001-02-02          1           4  
预期产量

  date          groupid         foo     statistics
  2001-01-25          1           1             10
  2001-01-28          1           2             10
  2001-02-02          1           4             11

您可以创建月周期为的新列,然后将其合并,这也是在
df1
中将
2001-02-31
更改为
2001-02-28
所必需的,因为
31。二月
不存在:

df1['per'] = df1.index.get_level_values('date').to_period('M')
df2['per'] = df2.date.dt.to_period('M')
print (df1)
                    statistics     per
date       groupid                    
2001-01-31 1                10 2001-01
2001-02-28 1                11 2001-02

print (df2)
        date  groupid  foo     per
0 2001-01-25        1    1 2001-01
1 2001-01-28        1    2 2001-01
2 2001-02-02        1    4 2001-02

print (pd.merge(df2, df1.reset_index(level=1), on=['per','groupid'], how='right')
         .drop('per', axis=1))

        date  groupid  foo  statistics
0 2001-01-25        1    1          10
1 2001-01-28        1    2          10
2 2001-02-02        1    4          11

哈,二月的日期是我输入数据(从远程面板)时的一个输入错误,你抓住我了!我先用5分钟找出为什么没有datetime;)