查找元素更改值numpy的索引 [英] Find index where elements change value numpy

查看:169
本文介绍了查找元素更改值numpy的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有

>>> v
array([1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 3, 4, 3, 4, 3, 4, 5, 5, 5])

是否有一种有效的numpy方法来查找值变化的每个索引?例如,我想要一些结果,例如

Is there an efficient numpy way to find each index where the value changes? For instance, I would want some result like,

>>> index_of_changed_values(v)
[0, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16]

如果使用一些numpy例程是不可能的,那么在python中执行此操作的快速方法是什么?因为我是一个刚性的初学者,所以我可以参考一些好的numpy教程。

If this is not possible with some numpy routine, what is a fast way to do it in python? It would also be useful to me to be referred to some good numpy tutorials since I am a numpy beginner.

推荐答案

你可以得到numpy中的这个功能是通过比较每个元素与它的邻居;

You can get this functionality in numpy by comparing each element with it's neighbor;

v[:-1] != v[1:]


array([False, False, False, False,  True, False, False,  True,  True,
    True,  True,  True,  True,  True,  True,  True, False, False], dtype=bool)

获取你使用where函数的索引

to get the indices you use the "where" function

np.where(v[:-1] != v[1:])[0]

array([ 4,  7,  8,  9, 10, 11, 12, 13, 14, 15])

从这里你可以添加第一个元素并添加一个元素以获得你问题中的相同索引方案。

From here you can prepend the first element and add a one to get to the same indexing scheme you have in your question.

这篇关于查找元素更改值numpy的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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