如果两个日期相同,则在数据之后保留一周和一周。

huangapple go评论59阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月8日 12:55:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76428714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定