When i try to find even numbers with where() method in 1-D array, it returns me odd numbers. Why?

Question:

I am working on numpy and when i was trying numpy methods on my editor, i noticed an anormal situation for me.

Firstly, I created a numpy array (nd.array) like that:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

After that, I tried to get even numbers from the array and I wrote this code line:

even_numbers_in_array = np.where(arr%2 == 0) 

and I thought it should return a tuple that contains even numbers but it returns me opposite of that:

In [33]: even_numbers_in_array
Out[33]: (array([ 1,  3,  5,  7,  9, 11], dtype=int64),)

after this result, I was shocked because there are 9, 10, 11 values even if they are not in the array.
Can anybody explain that strange situation to me?

Thank you

I use spyder(anaconda3) editor and w11 operating system

Asked By: eminaruk

||

Answers:

You don’t need np.where:

>>> arr[arr % 2 == 0]
array([2, 4, 6, 8])

Note: np.where returns the index not the number itself.

>>> arr[np.where(arr % 2 == 0)[0]]
array([2, 4, 6, 8])

You are confused because you use a particular array [1, 2, 3, 4, 5, 6, 7, 8]. Try with another series:

arr = np.array([11, 12, 13, 14, 15, 16, 17, 18])

>>> np.where(arr % 2 == 0)
(array([1, 3, 5, 7]),)

>>> arr[arr % 2 == 0]
array([12, 14, 16, 18])
Answered By: Corralien
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.