我有这样的功能:
我使用curve_fit拟合我的数据。...编写了此代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
db = pd.read_excel("/Users/piero/Desktop/lavori/AIF/test.xlsx")
M0=np.array(db['M0'])
t_time=np.array(db['time'])
def func(t, K, t0, a, b):
if t > t0 :
f = K * ((t-t0)**a) * np.exp(-(t-t0)/b)
return f
return 0
params_guess=[2,3,4,1]
popt,pcov= curve_fit(func,t_time,M0,p0=params_guess)
我有这个错误
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
因此,我知道在函数func中,我无法将数组与数字进行比较,但我需要将t> t0条件设为合适的值。有人知道怎么做吗?
您想评估在数组t
的每个元素处编写的条件。使用整个数组作为t
调用该函数,该数组可能跨越点t0
。在Numpy中,您可以通过多种方式进行这种条件评估,但最简单的方法是:
def func(t, K, t0, a, b):
return np.where(t > t0, K * (t - t0) ** a * np.exp(-(t - t0) / b), 0.0)
这应理解为:“在条件t > t0
为真的数组索引处,从第一个表达式返回值,而在其他值处返回0.0。”