查找元素更改值 numpy 的索引 [英] Find index where elements change value numpy
问题描述
假设我有
<预><代码>>>>v数组([1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 3, 4, 3, 4, 3, 4, 5, 5, 5])是否有一种有效的 numpy 方法可以找到值发生变化的每个索引?例如,我想要一些类似的结果,
<预><代码>>>>index_of_changed_values(v)[0, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16]如果使用某些 numpy 例程无法做到这一点,那么在 python 中快速完成的方法是什么?由于我是一个 numpy 初学者,因此参考一些好的 numpy 教程对我也很有用.
你可以在 numpy 中通过将每个元素与其邻居进行比较来获得这个功能;
v[:-1] != v[1:]数组([假,假,假,假,真,假,假,真,真,真,真,真,真,真,真,真,假,假],dtype=bool)
使用where"函数获取索引
np.where(v[:-1] != v[1:])[0]数组([ 4, 7, 8, 9, 10, 11, 12, 13, 14, 15])
从这里您可以添加第一个元素并添加一个以获得与您的问题相同的索引方案.
Suppose I have
>>> v
array([1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 3, 4, 3, 4, 3, 4, 5, 5, 5])
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]
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.
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)
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屋!