Reputation: 361
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?
Upvotes: 0
Views: 230
Reputation: 10501
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")
]
?
Upvotes: 1