【问题标题】:Querying a DataFrame values from a specific year查询特定年份的 DataFrame 值
【发布时间】:2018-12-14 06:18:57
【问题描述】:

我有一个从天气数据创建的 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)

DataFrame 的图片:

【问题讨论】:

  • 你可以这样做:daily_df = df[df['Date'].dt.year == 2015].reset_index(drop=True)
  • 您好,这似乎不起作用。我收到错误“AttributeError: Can only use .dt accessor with datetimelike values”

标签: pandas datetime


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2012-02-14
    相关资源
    最近更新 更多