Search code examples
pythonnumpymodulo

How to get only odd numbers in array and square them using numpy for python?


I've done this without NumPy in Python:

def fun_list(list_, x):
#set list to odd numbers in list_ raised to number x
s=[]    
s= [i**x for i in list_ if (i%2)!=0]
list_=s          
print(list_)

Testing the function:

list1 = [1, 2, 3, 4]
list2 = [2, 3, 4, 5]
print(fun_list(list1, 2))
print(fun_list(list2, 3))    

Results:

[1, 9]
None
[27, 125]
None

NOW need to do it using NumPy, which I don't understand and can't find much about it online and what I find doesn't make sense to me. This is what I've tried:

import math 
#set list to odd numbers in list_ raised to number x
a=np.array([array_])
pwr=x
a=np.array([a if np.mod(a)!=0])
a=np.array([np.power(a,pwr)])
print (a)

Testing the function:

import numpy as np
array1 = np.array([1, 2, 3, 4])
array2 = np.array([2, 3, 4, 5])
print(fun_array(array1, 2))
print(fun_array(array2, 3))

Results:

File "<ipython-input-161-fc4f5193f204>", line 21
a=np.array([a if np.mod(a)!=0])
                             ^
SyntaxError: invalid syntax

I am not understanding what to do to get only the odd numbers in the array using NumPy.


Solution

  • Here you go:

    a=np.array([1,2,3,4,5,6])
    power = 2
    answer = (a[a%2==1])**power
    print (answer)
    

    Output

    [ 1  9 25]
    

    Here, the operation a%2==1 returns a Boolean array array([ True, False, True, False, True, False], dtype=bool) which is True if the remainder/modulus after dividing by 2 (which is given by a%2) value is 1 and False if its 0. Using this as an argument for your array a will return only the a values for which the argument is 'True'. This yields only odd numbers from a. The ** then squares these odd numbers. In case you want the even numbers, one way would be to put a%2==0 in your condition.