Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to applied a user defined function to each of the numpy array elements

I would like to apply a function to each of the element of my numpy array. I did some thing like this; but it still print the original array. What might be the problem?

def my_func(k):
    3.15+ k*12**45+16

arr = np.array([12,45,45],[12,88,63])
my_func(arr)
print (arr)
like image 309
user3841581 Avatar asked May 22 '15 19:05

user3841581


People also ask

Which function is used to add two NumPy arrays element wise?

add() function is used when we want to compute the addition of two array. It add arguments element-wise. If shape of two arrays are not same, that is arr1.

Which function is used to find the type of NumPy array?

The astype() function creates a copy of the array, and allows you to specify the data type as a parameter. The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or you can use the data type directly like float for float and int for integer.

What does the NumPy () method do?

NumPy aims to provide an array object that is up to 50x faster than traditional Python lists. The array object in NumPy is called ndarray , it provides a lot of supporting functions that make working with ndarray very easy. Arrays are very frequently used in data science, where speed and resources are very important.


1 Answers

Try this:

def my_func(k):
    return 3.15 + k * 12 ** 45 + 16

arr = np.array([[12, 45, 45], [12, 88, 63]])
print my_func(arr)

Output:

[[4.388714385610605e+49 1.6457678946039768e+50 1.6457678946039768e+50]
 [4.388714385610605e+49 3.218390549447777e+50 2.3040750524455676e+50]]

The problem is that you don't return a value from your function. Then you don't define correctly the data for np.array. Finally, you don't set the my_func's result in a variable.

like image 70
JuniorCompressor Avatar answered Oct 27 '22 09:10

JuniorCompressor