pandas - 查询特定年份的 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)
数据帧的图像:
解决方案
我通过添加仅包含年份的行然后以这种方式查询来解决此问题,但必须有更好的方法来做到这一点?
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
推荐阅读
- django-rest-framework - 如何在 drf-aysg swagger web UI 中显示棉花糖 sheme 作为 request_body 的示例
- elasticsearch - 通过 Elasticsearch 中的索引位置获取文档
- reactjs - 鸽子地图标记问题
- angular - 即使连接到数据源,如何强制分页器长度?
- javascript - 我们可以在多个数组上使用一个 Array.filter() 方法吗?
- c# - 使用 NUnit 对 DateTime 控制器进行单元测试
- java - Spring数据jpa和具有某种关系的实体
- python - While 循环忽略循环外的变量,这会在明确定义时导致未定义的错误
- reactjs - 图标应该有 `type` 属性或 `component` 属性或 `children`?
- jquery - 当我使用 jquery 选择另一个选择框的空值时,如何重置选择框?