0

Let's consider the following array: x = np.array(["john", "john", "ellis", "lambert", "john"])

Is there a way to compare every element of the array to the previous and return a boolean array. In the present example, the result would be [True,False,False,False].

Is there any function (similar as np.diff) to achieve that?

2
  • 6
    Using slicing x[1:] == x[:-1]? Commented Aug 1, 2017 at 20:32
  • 1
    You should probably just be using a list for this... Commented Aug 1, 2017 at 20:34

3 Answers 3

3

You can do this with indexing:

array[:-1] == array[1:]
Sign up to request clarification or add additional context in comments.

Comments

1

The first item in the list cannot be compared with a previous value and should likely default to np.nan.

To maintain the same shape as the original array:

>>> np.concatenate([np.array([np.nan]), x[:-1] == x[1:]])
array([ nan,   1.,   0.,   0.,   0.])

The inclusion of nan changes to type to floats.

Comments

1

Using indexing, you can do this with ease.

import numpy as np

x = np.array(["john", "john", "ellis", "lambert", "john"])

print x[1:] == x[:-1]

The statement x[1:] == x[:-1] works because the == operand returns Boolean values, and in this case presented in an array due to the types of the two compared items.

x[1:] represents all the elements in the array except item 0, the first item, while x[:-1] represents all the elements in the array except the last item.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.