6

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)
3
  • wouldn't just 3.15 + arr*12**45+16 work? Commented May 22, 2015 at 19:42
  • Do you maybe want to return something from that function and use arr instead of ar and reassign to arr? Commented May 22, 2015 at 19:43
  • it does but what i have a much more complex function which take as a parameters a single value but i want to apply it to all the array? Commented May 22, 2015 at 19:44

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It works. Thank you. I did not save the results. in another array. Thank you
@ JuniorCompressor i have a problem tough, when i try it on a vector, i have an error like this : TypeError: only length-1 arrays can be converted to Python scalars
0

If you do this:

import numpy as np

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

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

you get this:

[[12 45 45]
 [12 88 63]]
[[4.388714385610605e+49 1.6457678946039768e+50 1.6457678946039768e+50]
 [4.388714385610605e+49 3.218390549447777e+50 2.3040750524455676e+50]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.