【问题标题】:Compare numpy array and datetime without year比较没有年份的numpy数组和日期时间
【发布时间】:2019-08-15 14:02:06
【问题描述】:

我有一个 numpy 数组,我希望按日期时间过滤它。我目前具有将输入日期时间(startend)与数据框进行比较的功能,如下所示:

    if trim:
        columns = input_hdf.columns.get_level_values(0)
        print(str(columns))
        print(start)
        print(end)
        if start is not None and end is not None:
            mask = (columns >= start) & (columns <= end)
        elif start is not None:
            mask = (columns >= start)
        elif end is not None:
            mask = (columns <= end)
        else:
            # Should never reach this point, but just in case - mask will not affect the data
            mask = True
        input_hdf = input_hdf.loc[:, mask]

但是,我想为开始和结束添加功能以指定为“一年中的一天”,其中年份与比较无关 - 如果这一天晚于 10 月 1 日,则将其排除在外2001 年或 2021 年。

我目前正在通过以下方式将整数值转换为日期时间:

start = datetime.strptime(start, '%d-%m-%Y') if start else None

默认年份为 1900,这将成为比较的一部分。

【问题讨论】:

标签: python pandas numpy dataframe


【解决方案1】:

pandas 对日期和时间有更好的支持。这个答案利用了mm-dd 形式的日期时间字符串是可排序的这一事实:

dates = <ndarray of dates>
s = pd.Series(dates, index=dates).dt.strftime('%m-%d')

# Select between Oct 1 and Dec 31 of all years
cond = ('10-01' <= s) & (s <= '12-31')
selected = s[cond].index.values

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    相关资源
    最近更新 更多