首页 > 解决方案 > 查询特定年份的 DataFrame 值

问题描述

我有一个从天气数据创建的 pandas 数据框,它显示了 2005 年至 2015 年每天的高温和低温。我希望能够查询我的数据框,使其仅显示 2015 年的值。有没有办法在不首先将日期时间值更改为仅显示年份的情况下执行此操作(即不首先创建 strtime(%y) ) ?

数据框创建:

df=pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
df['Date']=pd.to_datetime(df.Date)
df['Date'] = df['Date'].dt.strftime('%m-%d-%y')

尝试查询:

daily_df=df[df['Date']==datetime.date(year=2015)]
Error: asks for a month and year to be specified.

数据:

NOAA 数据集已存储在文件 data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv 中。这项任务的数据来自国家环境信息中心 (NCEI) 每日全球历史气候学网络 (GHCN-Daily) 的一个子集。GHCN-Daily 包含来自全球数千个地面站的每日气候记录。

分配数据文件中的每一行对应于一个观察值。

为您提供了以下变量:

id : station identification code
date : date in YYYY-MM-DD format (e.g. 2012-01-24 = January 24, 2012)
element : indicator of element type
TMAX : Maximum temperature (tenths of degrees C)
TMIN : Minimum temperature (tenths of degrees C)
value : data value for element (tenths of degrees C)

数据帧的图像:

在此处输入图像描述

标签: pandasdatetime

解决方案


我通过添加仅包含年份的行然后以这种方式查询来解决此问题,但必须有更好的方法来做到这一点?

df['Date']=pd.to_datetime(df['Date']).dt.strftime('%d-%m-%y')
df['Year']=pd.to_datetime(df['Date']).dt.strftime('%y')
daily_df = df[df['Year']=='15']
return daily_df

推荐阅读