繁体   English   中英

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

[英]Need to filter dates by month in pandas dataframe

以 2010-01-01 格式获取跨越多年的温度数据。 我想从六月中分离出临时数据,但不确定如何过滤它。 通常我使用的方法是df[df['date'] == 2016]但这只能按年份解析。

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

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

数据帧的打印头。

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)检查数据类型。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM