我有一个大型 pandas 数据框,其中有与之关联的每小时数据。然后我想将其解析为对每小时数据求和的“每月”数据。但是,月份不一定是日历月,它们通常从一个月的中旬开始,到下个月的中旬结束。
我可以构建一个列表,列出每个日期范围内的“月份”并循环遍历它,但我认为有更好的方法可以通过 pandas 来做到这一点。
这是我当前的代码,最后一行抛出错误,这是问题的症结所在:
dates = pd.Series(pd.date_range('1/1/2015 00:00','3/31/2015 23:45',freq='1H'))
nums = np.random.randint(0,100,dates.count())
df = pd.DataFrame({'date':dates, 'num':nums})
month = pd.DataFrame({'start':['1/4/2015 00:00','1/24/2015 00:00'], 'end':['1/23/2015 23:00','2/23/2015 23:00']})
month['start'] = pd.to_datetime(month['start'])
month['end'] = pd.to_datetime(month['end'])
month['num'] = df['num'][(df['date'] >= month['start']) & (df['date'] <= month['end'])].sum()
我想要一个类似的输出:
start end num
0 2015-01-04 2015-01-23 23:00:00 33,251
1 2015-01-24 2015-02-23 23:00:00 39,652
当然,我不明白。
请您参考如下方法:
pd.merge_asof 仅适用于 pandas 0.19
pd.merge_asof的组合+ query + groupby
pd.merge_asof(df, month, left_on='date', right_on='start') \
.query('date <= end').groupby(['start', 'end']).num.sum().reset_index()
解释
pd.merge_asof
来自文档
For each row in the left DataFrame, we select the last row in the right DataFrame whose ‘on’ key is less than or equal to the left’s key. Both DataFrames must be sorted by the key.
但这只考虑了开始日期。
查询
我用 query 处理 end 日期,因为我现在方便地在 pd.merge_asof 之后在我的数据框中有 end/p>
groupby
我相信这部分是显而易见的`
