英文:
Filtering pandas dataframe to restrict within a given range of dates
问题
我有一个类似这样的pandas数据框:
2684 A878 2015-01-01 False M13
2685 A878 2015-01-01 False M50
2686 A879 2015-01-01 False M96
5735 A879 2015-01-02 False M19
... ... ... ... ...
89487 A879 2015-01-30 False M38
89488 A879 2015-01-30 False M35
89489 A879 2015-01-30 False M33
89490 A879 2015-01-30 True M66
89491 A879 2015-01-30 False M4
我想要通过第二列的特定值(== A879)和从日期的特定偏移量来筛选数据框。例如,如果我的第二列值是A879,我的期望日期是2015-01-15,那么我想要所有具有第二列A879且在2015-01-15之前超过2天但少于5天的行。所以它应该看起来像这样。
89490 A879 2015-01-13 True M66
89491 A879 2015-01-14 False M4
有没有一种简便的方法来做到这一点?
英文:
I have a pandas data frame that looks like this
2684 A878 2015-01-01 False M13
2685 A878 2015-01-01 False M50
2686 A879 2015-01-01 False M96
5735 A879 2015-01-02 False M19
... ... ... ... ...
89487 A879 2015-01-30 False M38
89488 A879 2015-01-30 False M35
89489 A879 2015-01-30 False M33
89490 A879 2015-01-30 True M66
89491 A879 2015-01-30 False M4
I would like to filter the data frame by a particular value for the second column( == A879) and by a particular offset from a date. For example if my second column value is A879 and my desired date is 2015-01-15 then I want all the rows that has A879 for the second column and more that 2 but less than 5 days before the 2015-01-15. So it should look like.
89489 A879 2015-01-12 False M33
89490 A879 2015-01-13 True M66
89491 A879 2015-01-14 False M4
Is there a nice way to do this?
答案1
得分: 1
import datetime as dt
REFERENCE_DATE = dt.date(2015, 1, 15)
df["date"] = pd.to_datetime(df["date"])
df[
df["date"].dt.date.between(
REFERENCE_DATE - dt.timedelta(days=5), REFERENCE_DATE - dt.timedelta(days=2)
)
& df["code"].eq("A879")
]
英文:
How about
import datetime as dt
REFERENCE_DATE = dt.date(2015, 1, 15)
df["date"] = pd.to_datetime(df["date"])
df[
df["date"].dt.date.between(
REFERENCE_DATE - dt.timedelta(days=5), REFERENCE_DATE - dt.timedelta(days=2)
)
& df["code"].eq("A879")
]
?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论