简体   繁体   中英

“The truth value of an array with more than one element is ambiguous” in python

this is how I got the two arrays (array 1 and array2) for my function:

x = np.arange(-5, 5,0.01)
prob=stats.norm.pdf(x,0,1)
prob_array=numpy.array(prob).reshape(1000,1) #array1
x_tran=m.transpose()
x_tran_array=array(x_tran)
mu_array=array(mu)           # mu is stock return 
mu_array1=numpy.array(mu_array).reshape(54966,1)
sigma_array=array(sigma)     #sigma is the historical volatility
sigma_array1=numpy.array(sigma_array).reshape(54966,1)
mu1_mat=mat(ones((1,1000)))  #for matrix calculation
original_x=mu_array1*mu1_mat+sigma_array1*x_tran_array #array2

I defined a function:

def TK_value(z,p):
    if z >= 0:
        utility=z**0.88
        prob=(p**0.61)/(p**0.61+(1-p)**0.61)**(1/0.61)
    else:
        utility= -2.25*(-z)**0.88
        prob=(p**0.69)/(p**0.69+(1-p)**0.69)**(1/0.69)
    return utility*prob


tks=TK_value(original_x,prob_array)

I have two arrays with original_x with shape((54966, 1000) and prob_array with shape (1000,1). I want to use original_x as z and prob_array as p in this function.

But the error is:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Welcome to SO: The problem seems to be this line: if z >= 0: If you use the '>'/'<' operator on an array it will return the following:

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> a > 2
array([False, False,  True])

This array can't be converted to bool by default, you have to be more specific, for example by using any() to test if atleast one element falls under the given condition. Numpy arrays can do it like this: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.any.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM