Remove consecutive duplicates in a NumPy array(删除 NumPy 数组中的连续重复项)
问题描述
我想删除彼此跟随的重复项,但不删除整个数组中的重复项.另外,我想保持顺序不变.
I would like to remove duplicates which follow each other, but not duplicates along the whole array. Also, I want to keep the ordering unchanged.
所以如果输入是 [0 0 1 3 2 2 3 3]
输出应该是 [0 1 3 2 3]
So if the input is [0 0 1 3 2 2 3 3]
the output should be [0 1 3 2 3]
我找到了一种使用 itertools.groupby()
的方法,但我正在寻找更快的 NumPy 解决方案.
I found a way using itertools.groupby()
but I am looking for a faster NumPy solution.
推荐答案
a[np.insert(np.diff(a).astype(np.bool), 0, True)]
Out[99]: array([0, 1, 3, 2, 3])
一般的思路是使用diff
来查找数组中两个连续元素之间的差异.然后我们只索引那些给出 non-zero
差异元素的元素.但是由于 diff
的长度短了 1.所以在索引之前,我们需要 insert
将 True
到 diff 数组的开头.
The general idea is to use diff
to find the difference between two consecutive elements in the array. Then we only index those which give non-zero
differences elements. But since the length of diff
is shorter by 1. So before indexing, we need to insert
the True
to the beginning of the diff array.
说明:
In [100]: a
Out[100]: array([0, 0, 1, 3, 2, 2, 3, 3])
In [101]: diff = np.diff(a).astype(np.bool)
In [102]: diff
Out[102]: array([False, True, True, True, False, True, False], dtype=bool)
In [103]: idx = np.insert(diff, 0, True)
In [104]: idx
Out[104]: array([ True, False, True, True, True, False, True, False], dtype=bool)
In [105]: a[idx]
Out[105]: array([0, 1, 3, 2, 3])
这篇关于删除 NumPy 数组中的连续重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:删除 NumPy 数组中的连续重复项


- pytorch 中的自适应池是如何工作的? 2022-07-12
- 沿轴计算直方图 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01