过滤熊猫中两个日期之间的行

时间:2021-02-09 15:45:32

标签: python python-3.x pandas dataframe

我有一张包含日期、销售额和利润的工作表。数据是10年的历史数据。现在,我想过滤每年 1 月 1 日到 2 月 9 日之间的销售额。我该怎么做?

3 个答案:

答案 0 :(得分:3)

首先,您要确保您的 Date 是日期时间类型:

df['Date'] = pd.to_datetime(df['Date'])

然后您可以提取月份和日期并使用 loc 进行过滤:

month_day = df['Date'].dt.month * 100 + df['Date'].dt.day

df.loc[month_day.between(101, 209)]

答案 1 :(得分:2)

不如 Quang Hoangs 方法简单,但可能更易读/易懂:

df[(df['Date'].dt.month == 1) | ((df['Date'].dt.month == 2) & (df['Date'].dt.day <= 9))]

答案 2 :(得分:2)

您还可以使用 DateTimeIndex 对象的 dayofyear 属性:

给定日期是 dtype 日期时间,

df[df['Date'].dt.dayofyear < 41]

要获得每年的前 40 天,即 1 月的 31 天和 2 月的 9 天。

如果 Date 在索引中,那么您不需要 dt 访问器:

df[df.index.dayofyear < 41]