python - If/Then apply different function depending on each value in array
问题描述
I have an allegedly easy to solve question, but i still cannot figure it out:
I have an array with 1000 numbers called "mu" like this:
array([2.25492522e-01, 2.21059993e-01, 2.16757006e-01,....)
Now i need to plug these values in two different functions: For numbers in the array, that are less than 0.009, i need to use equation1:
nu = 1 - 5.5 * mu**(0.66) + 3.77 * mu
For all other numbers in the array, i need to plug these into equation2:
nu = 0.819**(-11.5*mu)+0.0975**(-70.1*mu)
In the end, i need an array of the function values "nu".
I gave this code a try, but it didn't work
for item in mu:
if item < 0.009:
nu = 1 - 5.5 * mu**(0.66) + 3.77 * mu
else:
nu = 0.819**(-11.5*mu)+0.0975**(-70.1*mu)
print nu
How can I tell Python to put the right numbers in?
解决方案
一个问题是您没有item
在for
循环中使用。您也不是附加到列表或分配给新数组来存储结果。无论如何,NumPy 具有为此任务设计的特定功能。例如,使用numpy.where
:
def func1(x):
return 1 - 5.5 * x**(0.66) + 3.77 * x
def func2(x):
return 0.819**(-11.5*x)+0.0975**(-70.1*x)
res = np.where(mu < 0.009, func1(mu), func2(mu))
虽然您可能会觉得处理的计算量是所需的两倍,但效率低下,但矢量化操作的好处远远超过了这一点。