[英]How to get all dates (month, day and year) between two dates in python?
[英]How to slice a pandas DataFrame between two dates (day/month) ignoring the year?
我想在 4 月 15 日至 9 月 16 日之间使用 DatetimeIndex 筛选 pandas DataFrame 多年。 之后我想给掩码设置一个值。
我希望有一个类似于 between_time between_time()
的 function ,但这不存在。
我的实际解决方案是在独特的年份中循环。
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():
# normal approche
# df[f'{year}-{start_date}':f'{year}-{end_date}'] = 1
# similar approche slightly faster
df.iloc[df.index.get_loc(f'{year}-{start_date}'):df.index.get_loc(f'{year}-{end_date}')+1]=1
是否存在可以避免循环并可能提高性能的解决方案?
要获取 4 月 1 日到 10 月 31 日之间的日期,如何使用月份?
df.loc[df.index.month.isin(range(4, 10)), 'target'] == 1
如果你想要 map 任何日期/时间,只是忽略年份,你可以将年份替换为 2000(闰年)并使用:
s = pd.to_datetime(df.index.strftime('2000-%m-%d'))
df.loc[(s >= '2000-04-15') & (s <= '2020-09-16'), 'target'] = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.