英文:
Keep one week and one week after data if two dates are same
问题
我有一个数据集,看起来像这样:
我想保留在“Date”等于“Fdate”的情况下前一周和后一周的数据。例如,在给定的数据示例中,1031列中的1/16/2011与1/16/2011相同,然后我想根据日期保留从1/9/2011到1/23/2011的数据。
我该如何实现这一目标?
提前感谢您。
英文:
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
答案1
得分: 1
你可以转换为日期时间,加上 ± 1W,并使用 between
进行选择:
df[['Date', 'Fdate']] = df[['Date', 'Fdate']].apply(pd.to_datetime)
delta = pd.DateOffset(days=7)
# 或者
# delta = pd.to_timedelta('7D')
df.loc[df['Date'].between(df['Fdate'].sub(delta), df['Fdate'].add(delta))]
输出:
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论