【问题标题】:How to filter a pandas DataFrame with DatetimeIndex for multiple years in a range between a start date and an end date?如何在开始日期和结束日期之间的范围内使用 DatetimeIndex 过滤多年的 Pandas DataFrame?
【发布时间】:2022-12-13 21:10:18
【问题描述】:

我想在 4 月 15 日到 9 月 16 日之间使用 DatetimeIndex 筛选一个 pandas DataFrame 多年。之后我想给掩码设置一个值。

我希望有一个类似于between_time() 的功能,但这不存在。

我的实际解决方案是在独特的年份中循环。

最小的例子

import pandas as pd

df = pd.DataFrame({'target':0}, index=pd.date_range('2020-01-01', '2022-01-01', freq='H'))

start_date = "04-15"
end_date = "09-16"
for year in df.index.year.unique():
    df[f'{year}-{start_date}':f'{year}-{end_date}'] = 1

是否存在可以避免循环并可能提高性能的解决方案?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    要获取 4 月 1 日到 10 月 31 日之间的日期,如何使用月份?

    df.loc[df.index.month.isin(range(4, 10)), 'target'] == 1
    

    如果你想映射任何日期/时间,只是忽略年份,你可以将年份替换为 2000(闰年)并使用:

    s = pd.to_datetime(df.index.strftime('2000-%m-%d'))
    df.loc[(s >= '2000-04-01') & (s <= '2020-09-15'), 'target'] = 1
    

    【讨论】:

    • 如果我想要完整的 4 月和 9 月,这是可行的,但是如果我从 4 月 15 日开始会怎样?
    • 不是最直接的,但请参阅更新
    • 如果之后重置索引,这可能是一个可行的方法。我必须考虑这个解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多