如何在numpy数组中删除相邻的重复值?

问题描述:

给定一个numpy数组,我希望删除相邻的重复非零值和所有零值.例如,对于这样的数组:[0,0,1,1,1,2,2,0,1,3,3,3],我想将其转换为:[1,2,1,3].你知道怎么做吗?我只知道np.unique(arr),但是它将删除所有重复的值并保持零值.预先谢谢你!

Given a numpy array, I wish to remove the adjacent duplicate non-zero value and all the zero value. For instance, for an array like that: [0,0,1,1,1,2,2,0,1,3,3,3], I'd like to transform it to: [1,2,1,3]. Do you know how to do it? I just know np.unique(arr) but it would remove all the duplicate value and keep the zero value. Thank you in advance!

对于以下问题,可以将itertools中的groupby方法与列表理解结合使用:

You can use the groupby method from itertools combined with list comprehension for this problem:

from itertools import groupby
[k for k,g in groupby(a) if k!=0]

# [1,2,1,3]

数据:

a = [0,0,1,1,1,2,2,0,1,3,3,3]