What does this: s[s[1:] == s[:-1]] do in numpy?

前端 未结 4 636

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.

What does th

4条回答
  •  无人及你
    2020-12-30 03:07

    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
    

    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)
    

    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.

提交回复
热议问题