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

和自甴很熟 提交于 2020-12-04 11:45:42

问题


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.


回答1:


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.




回答2:


The power of numpy is that it allows you to operate on entire array in a single operation. This is called vectorization or vectorizing. Under the hood there are loops to do this of course, but they are written in the C language and highly optimized so they run orders of magnitude faster than anything you can achieve with pure python.

So when you write a function using numpy, your number one goal is to have numpy do all the work. Ideally there should be no explicit loops, only calls that operate on entire arrays all at once. Fortunately, numpy provides all the necessary utilities to make this possible in your case.

Here is a step by step guide then:

First, convert your input into an array. Arrays are just like lists in many ways, with the difference that you can do vectorized operations on them. Most numpy functions will silently convert their inputs to an array if you pass in a list, but we will do it explicitly:

def numpy_fun_list(list_, x):
    arr = np.array(list_)

So far so good. All further operations will be done to arr instead of list_.

Next you'll want to filter out the even elements. The easiest way to do this is by masking the array. When you index a numpy array with a Boolean array of the same size, it will select the elements that are True in the Boolean array and discard the rest. For example:

>>> data = np.array([1, 2, 3, 4])
>>> mask = np.narray([True, False, False, True])
>>> data[mask]
array([1, 4])

All the conditional and comparison operators create such Boolean arrays. In your case, you want to check if a number is odd, so you use modulo just like in Python, except that modulo operates on each element of the array:

    mask = (arr % 2) == 1

The operator == is what turns the result of the modulo operation into a Boolean mask:

    arr = arr[mask]

Now we need to raise each element of the remaining arr to the power x. As you guessed, that's what np.power does:

    arr = np.power(arr, x)

That's it. Now you can return or print your result. Actually, a little note about that:

Your original function prints the result to the screen but doesn't return it. The return value of the function is implicitly None, which is why you see all those Nones printed. If you don't return it, there's not much you can do with the computed list, making the whole function fairly useless. My recommendation is to replace print (list_) with return list_.



来源:https://stackoverflow.com/questions/51617421/how-to-get-only-odd-numbers-in-array-and-square-them-using-numpy-for-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!