合并DateTimeIndex与月 - 年

时间:2017-01-24 09:47:31

标签: python pandas

我有两个数据框。一个人有一个精确的(每日)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

1 个答案:

答案 0 :(得分:1)

您可以在merge之后创建包含月份周期的新列,然后在2001-02-31中创建2001-02-28df1也需要更改31. February,因为{{ 1}}不存在:

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
相关问题