0

In the example code below

import numpy as np

def f(x):
    print(x)

x = np.array([[ 0.31432202,  7.94263361],
              [-0.5346868,   1.93901039],
              [-0.47571535,  4.17720033]])

np.vectorize(f)(x[0,:])

As output, I expected to get something like

[ 0.31432202  7.94263361]

Instead I get

0.31432202
0.31432202
7.94263361

Can anyone tell me what is wrong with it? Thank you

1 Answer 1

2

How much of the np.vectorize docs did you read?

In [129]: def f(x):
     ...:     print(x)
     ...: 
     ...: x = np.array([[ 0.31432202,  7.94263361],
     ...:               [-0.5346868,   1.93901039],
     ...:               [-0.47571535,  4.17720033]])
In [130]: f1=np.vectorize(f)
In [131]: f1(1)
1
1
Out[131]: array(None, dtype=object)

f gets called twice, once to determine the return dtype, and once for each element. Try it with 3 elements:

In [132]: f1([1,2,3])
1
1
2
3
Out[132]: array([None, None, None], dtype=object)

Note that the return is an array with None. That's because your f doesn't have a return statement. It just does the print.

Why are you using np.vectorize? It has a clear performance disclaimer. It also talks about the return dtype and how it determines that. It's not a high performance way of calling a function that just prints something. It may be useful for running a function of several scalar values, and you want to take advantage of numpy broadcasting.

Read the docs.

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

2 Comments

Thank you! I've read the docs but it went unnoticed. Sorry if it was a stupid question... I don't intent using the function for printing the values (as it was just an example code) but for calculating a mathematical expression with the values in a row. Is there a more efficient way to do it?
I have in the past recommended including a print to better see what vectorize is doing. In this case it reveals the initial trial call. Specifying an otypes gets rid of that.

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.