这是什么:s [s [1:] == s [:-1]]在numpy中做什么? [英] What does this: s[s[1:] == s[:-1]] do in numpy?
问题描述
我一直在寻找一种方法来有效地检查numpy数组中的重复项,并偶然发现了使用此代码包含答案的问题.
I've been looking for a way to efficiently check for duplicates in a numpy array and stumbled upon a question that contained an answer using this code.
这行在numpy中是什么意思?
What does this line mean in numpy?
s[s[1:] == s[:-1]]
想要在应用代码之前先了解代码.在Numpy文档中查看了内容,但找不到此信息.
Would like to understand the code before applying it. Looked in the Numpy doc but had trouble finding this information.
推荐答案
切片[1:]
和[:-1]
表示除第一个以外的所有内容和除最后一个以外的所有内容数组的元素:
The slices [1:]
and [:-1]
mean all but the first and all but the last elements of the array:
>>> import numpy as np
>>> s = np.array((1, 2, 2, 3)) # four element array
>>> s[1:]
array([2, 2, 3]) # last three elements
>>> s[:-1]
array([1, 2, 2]) # first three elements
因此,比较将在每个元素s[x]
及其邻居" s[x+1]
之间生成布尔比较数组,该数组将比原始数组短(因为最后一个元素没有邻居):
therefore the comparison generates an array of boolean comparisons between each element s[x]
and its "neighbour" s[x+1]
, which will be one shorter than the original array (as the last element has no neighbour):
>>> s[1:] == s[:-1]
array([False, True, False], dtype=bool)
并使用该数组为原始数组建立索引,您将获得比较结果为True
的元素,即与邻居相同的元素:
and using that array to index the original array gets you the elements where the comparison is True
, i.e. the elements that are the same as their neighbour:
>>> s[s[1:] == s[:-1]]
array([2])
请注意,这仅标识相邻的重复值.
Note that this only identifies adjacent duplicate values.
这篇关于这是什么:s [s [1:] == s [:-1]]在numpy中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!