python - What does this: s[s[1:] == s[:-1]] do in numpy? -
i've been looking way efficiently check duplicates in numpy array , stumbled upon question contained answer using code.
what line mean in numpy?
s[s[1:] == s[:-1]] would understand code before applying it. looked in numpy doc had trouble finding information.
the slices [1:] , [:-1] mean all first , all last elements of array:
>>> import numpy np >>> s = np.array((1, 2, 2, 3)) # 4 element array >>> s[1:] array([2, 2, 3]) # last 3 elements >>> s[:-1] array([1, 2, 2]) # first 3 elements therefore comparison generates array of boolean comparisons between each element s[x] , "neighbour" s[x+1], 1 shorter original array (as last element has no neighbour):
>>> s[1:] == s[:-1] array([false, true, false], dtype=bool) and using array index original array gets elements comparison true, i.e. elements same neighbour:
>>> s[s[1:] == s[:-1]] array([2]) note identifies adjacent duplicate values.
Comments
Post a Comment