筛选pandas数据框以限制在给定日期范围内

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

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")
]

?

huangapple
  • 本文由 发表于 2020年1月4日 00:55:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582378.html
匿名

发表评论

匿名网友

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

确定