需要按月在熊猫数据框中过滤日期

时间:2019-11-23 21:20:10

标签: python pandas date dataframe filter

具有2010年1月1日格式的跨年温度数据。我想将六月的气温与外界隔离,不确定如何过滤。通常我使用的方法是 df[df['date'] == 2016],但这只能按年份解析。

2 个答案:

答案 0 :(得分:2)

IIUC,您可以在日期时间之上使用日期时间方法来访问月份

impot pandas as pd
rng = pd.date_range('2010-01-01','2011-01-01',freq='D')
df = pd.DataFrame({'dates':rng})

DataFrame的打印头。

print(df.head(5))
     dates
0 2010-01-01
1 2010-01-02
2 2010-01-03
3 2010-01-04
4 2010-01-05

使用.loc访问器通过dt.month方法过滤数据框:

df.loc[df['dates'].dt.month == 2]
     dates
31 2010-02-01
32 2010-02-02
33 2010-02-03
34 2010-02-04
35 2010-02-05
36 2010-02-06

使用pd.to_datetime

确保您的日期是正确的日期时间对象

使用print(df.dtypes)检查数据类型。

答案 1 :(得分:1)

您可以使用方法dt.month_name()

df[df['date'].dt.month_name() == 'June']