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

非 Y 不嫁゛ 提交于 2021-02-11 12:33:39

问题


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()


回答1:


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.



来源:https://stackoverflow.com/questions/63362238/the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!