Python提供了如何获取距离给定日期最近的日期

2024-04-18 23:26:24 发布

您现在位置:Python中文网/ 问答频道 /正文

   date
0  09-2019
1  10-2019
2  11-2019
4  01-2020
5  02-2020
7  04-2020

我有一个熊猫数据帧dates如上所示-这不是以任何方式排序的。我将dates列设置为datetime类型,并仅选择月份和年份,如下所示:

dates['date'] = pd.to_datetime(dates['date'], errors='ignore')
dates['date'] = dates['date'].dt.strftime("%m-%Y")

我想选择与给定日期最接近的行,设置如下:

latest_date = max(dates['date'])
latest_date = latest_date.strftime("%m-%Y")

这给了我05-2020。如何使用nearest方法从dates中选择距离^{最近的日期或相等的日期latest_date?示例的预期输出应该是04-2020

我试过这个:

dates.iloc[dates.index.get_loc(datetime.datetime(latest_date),method='nearest')]

但是我得到了一个AttributeError: type object 'datetime.datetime' has no attribute 'datetime'。这是否意味着我没有正确转换日期列


Tags: to数据类型datetimedate排序方式latest
2条回答

IIUC,您可以在列和所述latest_date之间的差异上使用idxmin

latest_date = '05-2020'
print (dates.loc[(pd.to_datetime(dates['date'])
                  -pd.to_datetime(latest_date)).abs().idxmin(), 
                 'date'])
'04-2020'

警告:如果对索引进行排序,则更安全,结果更可靠

#set 'date' as index
df = pd.read_clipboard(parse_dates=['date']).set_index('date')

#get the nearest date : 
df.index.sort_values().asof('05-2020')
Timestamp('2020-04-01 00:00:00')

相关问题 更多 >