我有一个数据集,其中每个观察值都有一个日期
。然后我有一个事件列表。我想过滤数据集并仅在日期在事件发生的 +/- 30 天内保留观察结果。另外,我想知道它最接近哪个事件。
例如,主数据集如下所示:
Product Date
Chicken 2008-09-08
Pork 2008-08-22
Beef 2008-08-15
Rice 2008-07-22
Coke 2008-04-05
Cereal 2008-04-03
Apple 2008-04-02
Banana 2008-04-01
生成
d = {'Product': ['Apple', 'Banana', 'Cereal', 'Coke', 'Rice', 'Beef', 'Pork', 'Chicken'],
'Date': ['2008-04-02', '2008-04-01', '2008-04-03', '2008-04-05',
'2008-07-22', '2008-08-15', '2008-08-22', '2008-09-08']}
df = pd.DataFrame(data = d)
df['Date'] = pd.to_datetime(df['Date'])
然后我有一列事件:
Date
2008-05-03
2008-07-20
2008-09-01
由
生成event = pd.DataFrame({'Date': pd.to_datetime(['2008-05-03', '2008-07-20', '2008-09-01'])})
目标(已编辑)
仅当 df['Date']
在 event['Date']
的一个月内时,我才想保留 df
中的行>。例如,第一个事件发生在 2008-05-03,所以我想保留 2008-04-03 和 2008-06-03 之间的观测值,并创建一个新列来告诉这个观测值最接近 2008 年的事件-05-03.
Product Date Event
Chicken 2008-09-08 2008-09-01
Pork 2008-08-22 2008-09-01
Beef 2008-08-15 2008-07-20
Rice 2008-07-22 2008-07-20
Coke 2008-04-05 2008-05-03
Cereal 2008-04-03 2008-05-03
最佳答案
使用numpy
广播并假设30天内
df[np.any(np.abs(df.Date.values[:,None]-event.Date.values)/np.timedelta64(1,'D')<31,1)]
Out[90]:
Product Date
0 Chicken 2008-09-08
1 Pork 2008-08-22
2 Beef 2008-08-15
3 Rice 2008-07-22
4 Coke 2008-04-05
5 Cereal 2008-04-03
关于python - 过滤日期在多个给定日期的 +/-30 天内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57949567/