Reputation: 157
I have a Pandas DataFrame with a 'DateTime' column. I need to filter out all rows in the DataFrame that have this date and add - 7 and + seven days to the target date.
It should be something like this: test = dataset.loc[-7:"4/17/2017":+7].hp1.values
What is the best way to achieve this?
Upvotes: 1
Views: 1107
Reputation: 863481
Idea is create datetimes above and below by Timedelta
and then filter with start and end datetimes, also for filter by column name add it to DataFrame.loc
:
#sample data
dataset = pd.DataFrame({'hp1':range(20)}, index=pd.date_range('04-09-2017', periods=20))
#print(dataset)
d = "4/17/2017"
date = pd.to_datetime(d)
td = pd.Timedelta(7, unit='d')
#alternative
#td = pd.offsets.DateOffset(days=7)
start = date - td
end = date + td
test = dataset.loc[start:end, 'hp1']
print (test)
2017-04-10 1
2017-04-11 2
2017-04-12 3
2017-04-13 4
2017-04-14 5
2017-04-15 6
2017-04-16 7
2017-04-17 8
2017-04-18 9
2017-04-19 10
2017-04-20 11
2017-04-21 12
2017-04-22 13
2017-04-23 14
2017-04-24 15
Freq: D, Name: hp1, dtype: int64
Upvotes: 1