删除具有相同时间戳numpy的行

时间:2014-03-08 00:54:40

标签: numpy duplicate-removal

我有一个numpy数组

TimeStamp  Col1 Col2
0           1    1.2
0           1.1  1.1
1           2    3
1           2.3  3.1
2           2.2  3.0 
3           3    4

我想要的最终数组没有重复的时间戳。对于给定的时间戳,我想要最后的已知值。例如,输出是

TimeStamp      Col1    Col2        
    0           1.1     1.1       
    1           2.3     3.1
    2           2.2     3.0 
    3           3       4

我显然可以在一个笨重的循环中做到这一点。但很想知道一个更优雅的numpy解决方案。感谢。

1 个答案:

答案 0 :(得分:1)

有多种方法可以做到这一点:

uniq = np.unique(arr)
indexes = np.searchsorted(arr, uniq, side='right') - 1

这个想法是找到价值变化的地方。结果是一系列索引,您可以将它们用于"花式索引。"类似的是:

indexes = np.where(np.diff(arr))

那个问题是它省略了最后一个元素。

或者你可以让NumPy为你提供唯一性所在的索引,但不幸的是它只支持返回第一个而不是最后一个,所以:

uniq = np.unique(arr, return_index=True)[1]
indexes = np.roll(uniq - 1, -1)
indexes[-1] = len(arr) - 1

另一个:

indexes = len(arr) - np.unique(arr[::-1], return_index=True)[1] - 1

这里我们反转输入以获得" last"来自unique的元素,然后在最后调整索引。

相关问题