The error message that I get when I run your code says:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
The problem is that a
is an array and v
a single value, so there is no single truth value in the comparison. If you intention is to check if v
is greater than all numbers in a
, use np.all(v>a)
. If you want to check if v
is greater than just some use np.any(v>a)
.
On Edit
You have now edited your question so much that it is now a new question. The entire point of the apply
method is that if f
is a Python function and v
is a numpy array, then f(v)
is probably not the array that you would get by applying f
to the elements of v
. Python is not a language that directly supports vectorized calculations. The reason that it sometimes seems that computations in numpy or pandas are as easy to vectorize as similar calculations in e.g. R is because of the way Python's duck-typing works. If a class defines the magic method __add__
then you can use +
to add elements of that class to each other in any way that you want. This is exactly what the people who created numpy have done (as well as other magic methods for things like *,/,<
etc.) So, if a function definition is something like def f(x): return x*x + 2*x + 3
where all the computational steps correspond to magic methods, then v.apply(f)
and f(v)
will work the same. Your test
function uses the keyword if
. There is not a magic method which can convert that part of the core language into something else.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…