如何在numpy数组中删除相邻的重复值? [英] How to remove the adjacent duplicate value in a numpy array?

查看:344
本文介绍了如何在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]

这篇关于如何在numpy数组中删除相邻的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆