I have a dataset looks like this:
I want to keep the data one week before and one week after if "Date" equals "Fdate." For example, in the given data sample, 1/16/2011 is same in both columns for 1031, then I want to keep the data from 1/9/2011 to 1/23/2011 (based on Date). How can I achieve this?
Thank you in advance
You can convert to datetime, add ± 1W and select with between
:
df[['Date', 'Fdate']] = df[['Date', 'Fdate']].apply(pd.to_datetime)
delta = pd.DateOffset(days=7)
# or
# delta = pd.to_timedelta('7D')
df.loc[df['Date'].between(df['Fdate'].sub(delta), df['Fdate'].add(delta))]
Output:
Gvkey Date Fdate prec
4 1031 2011-01-09 2011-01-16 5,2
5 1031 2011-01-10 2011-01-16 5,3
6 1031 2011-01-11 2011-01-16 5,4
7 1031 2011-01-12 2011-01-16 5,5
8 1031 2011-01-13 2011-01-16 5,6
9 1031 2011-01-14 2011-01-16 5,7
10 1031 2011-01-15 2011-01-16 5,8
11 1031 2011-01-16 2011-01-16 5,9