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

前端 未结 4 610

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

    It will show duplicates in a sorted array.

    Basically, the inner expression s[1:] == s[:-1] compares the array with its shifted version. Imagine this:

    1, [2, 3, ... n-1, n  ]
    -  [1, 2, ... n-2, n-1] n
    => [F, F, ...   F, F  ]
    

    In a sorted array, there will be no True in resulted array unless you had repetition. Then, this expression s[array] filters those which has True in the index array.

提交回复
热议问题