Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering even numbers in python [closed]

Tags:

python

numpy

just started with python and wanted to filter the even numbers from a numpy array:

>array = np.arange(2,10000)
>>print(array)

I know that the remainder of even no./2 should be 0, so part of the filtering condition should look somehow like this:

>if x%2 == 0

But no matter how, I always get an error of some kind. btw I'm using Python 3.

Thanks and Best

like image 605
palacinak Avatar asked Oct 16 '25 02:10

palacinak


1 Answers

One Liner as pointed by Mikel:

print(np.arange(2,10000,2))

This creates an array starting from 2 ending at 10k with a step size of 2 i.e every second number.

Or if you want to use modulus you can try like this:

ar = np.arange(2,10000)
ar = ar[ar%2==0]
print(ar)

Output:

array([   2,    4,    6, ..., 9994, 9996, 9998])

ar%2==0 creates a boolean mask to include only even numbers

like image 130
Mohammad Yusuf Avatar answered Oct 18 '25 16:10

Mohammad Yusuf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!