Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在数据帧中获取具有最近时间戳的行?_Python_Pandas_Dataframe_Timestamp - Fatal编程技术网

Python 如何在数据帧中获取具有最近时间戳的行?

Python 如何在数据帧中获取具有最近时间戳的行?,python,pandas,dataframe,timestamp,Python,Pandas,Dataframe,Timestamp,我有一个从列表中获取的时间戳,我需要在pandas数据帧中找到一行最接近我拥有的时间戳,即使是一组行也可以。 下面是示例数据帧 0 6160 Upper 12-7-2019 12:37:51.123572 1 6162 Upper 12-7-2019 12:39:22.355725 2 6175 Upper 12-7-2019 13:21:15.224157 3 6180 Upper 13-7-2019 06:04:29.157111 4 6263 Upper 13-7-2019 07:37:5

我有一个从列表中获取的时间戳,我需要在pandas数据帧中找到一行最接近我拥有的时间戳,即使是一组行也可以。 下面是示例数据帧

0 6160 Upper 12-7-2019 12:37:51.123572
1 6162 Upper 12-7-2019 12:39:22.355725
2 6175 Upper 12-7-2019 13:21:15.224157
3 6180 Upper 13-7-2019 06:04:29.157111
4 6263 Upper 13-7-2019 07:37:51.123572
我有一个时间戳
datetime.datetime(12,72019,16,41,20)

所以在这种情况下,我需要它在索引2处捕捉一行

谢谢你的帮助。 谢谢

您可以:

import datetime
dt = datetime.datetime(2019, 12, 7,16,41,20)

# d column is the date
minidx = (dt - df['d']).idxmin()

print(df.loc[[minidx]])

   a     b        c                          d
2  2  6175   Upper  2019-12-07 13:21:15.224157

datetime对象应该是datetime.datetime(2019,7,12,16,41,20)。参数的顺序是年、月、日、时、分、秒。看。
import pandas as pd
from datetime import datetime

# Input
ref_time = datetime(2019,7,12,16,41,20)
data = [[6160, 'Upper', '12-7-2019 12:37:51.123572'],
        [6162, 'Upper', '12-7-2019 12:39:22.355725'],
        [6175, 'Upper', '12-7-2019 13:21:15.224157'],
        [6180, 'Upper', '13-7-2019 06:04:29.157111'],
        [6263, 'Upper', '13-7-2019 07:37:51.123572']]

# Convert 2D list to DataFrame object
df = pd.DataFrame(data)

# Convert timestamp strings in column at index 2 to datetime objects
df.iloc[:, 2] = pd.to_datetime(df.iloc[:, 2], format='%d-%m-%Y %H:%M:%S.%f')

# Return row with minimum absolute time difference to reference time
print(df.loc[[(abs(df.iloc[:, 2]-ref_time)).idxmin()]])