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

前端 未结 4 635

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:14

    Check this out:

    >>> s=numpy.array([1,3,5,6,7,7,8,9])
    >>> s[1:] == s[:-1]
    array([False, False, False, False,  True, False, False], dtype=bool)
    >>> s[s[1:] == s[:-1]]
    array([7])
    

    So s[1:] gives all numbers but the first, and s[:-1] all but the last. Now compare these two vectors, e.g. look if two adjacent elements are the same. Last, select these elements.

提交回复
热议问题