Pandas从时间戳索引错误中找到最接近的值



在尝试从时间戳查找pandas df中的值时出现错误。我的df有一个时间戳索引

我的时间戳是:
time = datetime.datetime.fromtimestamp(sub_data_2[0, itime])
print(time)
2021-06-29 09:53:08.805039

我的df索引是这样的:

print(df.index)
DatetimeIndex(['2021-06-30 08:45:43', '2021-06-30 08:45:45',
'2021-06-30 08:45:46', '2021-06-30 08:45:47',
'2021-06-30 08:45:48', '2021-06-30 08:45:50',
'2021-06-30 08:45:51', '2021-06-30 08:45:52',
'2021-06-30 08:45:53', '2021-06-30 08:45:54',
...
'2021-06-28 16:34:22', '2021-06-28 16:34:23',
'2021-06-28 16:34:24', '2021-06-28 16:34:25',
'2021-06-28 16:34:26', '2021-06-28 16:34:27',
'2021-06-28 16:34:28', '2021-06-28 16:34:29',
'2021-06-28 16:34:30', '2021-06-28 16:34:31'],
dtype='datetime64[ns]', name='T', length=54143, freq=None)

使用索引。Get_loc函数:

index = df.index.get_loc(time, method='nearest')

错误是:

pandas.errors.InvalidIndexError: Reindexing only valid with uniquely valued Index objects

我看到这个错误可能来自于索引冲突的数据帧的连接,但这里不是这种情况。有什么想法吗?

您必须首先从索引中删除重复项。这里已经有答案了-答案

您可以像这样找到重复的索引:

df[df.index.duplicated(keep=False)]

我有两个问题:时间戳索引重复和排序。

df = df.sort_index()
df = df.drop_duplicates()

最新更新