我有一个 numpy 数组,我希望按日期时间过滤。我当前具有将输入日期时间(start
和end
)与数据框进行比较的功能,如下所示:
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,这将成为比较的一部分。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句