Python 3.x Scipy和Numpy升级生成;TypeError:无法将数组数据从数据类型(';O';)转换为数据类型(';float64';)”;

Python 3.x Scipy和Numpy升级生成;TypeError:无法将数组数据从数据类型(';O';)转换为数据类型(';float64';)”;,python-3.x,numpy,scipy,Python 3.x,Numpy,Scipy,我正在将一段代码从Python2.7转换为Python3.8 在Python2.7版本中,我不得不使用scipy和numpy的降级版本,以避免出现类型错误(见下文)。在Python3.8中,这些scipy和numpy的降级版本不再可用,我得到了这个错误,我无法修复 1。设置 先前版本:MacOS Catalina 10.15.7、Python 2.7.16、numpy 1.9.0、scipy 1.0.1 新版本:MacOS Catalina 10.15.7、Python 3.8.6、numpy

我正在将一段代码从Python2.7转换为Python3.8

在Python2.7版本中,我不得不使用scipy和numpy的降级版本,以避免出现类型错误(见下文)。在Python3.8中,这些scipy和numpy的降级版本不再可用,我得到了这个错误,我无法修复

1。设置

先前版本:MacOS Catalina 10.15.7、Python 2.7.16、numpy 1.9.0、scipy 1.0.1

新版本:MacOS Catalina 10.15.7、Python 3.8.6、numpy 1.20.3、scipy 1.4.0

2。代码

调用scipy.integrate.odeint时会发生这种情况:

y_trajectory = scipy.integrate.odeint(growth_a_derivs, y_start, t_array, atol=eps, args=myargs)
使用
growth\u a\u derivs
a函数,
y\u start,t\u array
numpy数组,带有dtype
float64
eps
一个float和
myargs
一个包含字典的长度为1的元组

3。错误

以下追溯性持久性有机污染物:

Traceback (most recent call last):
  
  <long blah blah blah>

  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyxcosmo/icosmo_cosmo.py", line 149, in growth_a
    result=growth_a_ode(cosmo, a, unnorm=unnorm)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyxcosmo/icosmo_cosmo.py", line 671, in growth_a_ode
    y_trajectory = scipy.integrate.odeint(growth_a_derivs, y_start, t_array, atol=eps, args=myargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/scipy/integrate/odepack.py", line 242, in odeint
    output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
在这里面,错误在一个编译的scipy
文件中,因此我无法进一步分析这个错误。我只知道对growth\u a\u derivs的调用没有问题(它的print()调用所有工作)。但我不知道这是一个棘手的问题还是棘手的问题,以及如何克服它

4。决心

由于下面的@RFoxtea答案,我能够理解这个问题。 我相信这个问题是由numpy版本的变化引起的。
growth\u a\u derivs
的输出为:

np.array([f1,f2])
与:

type(f1) = numpy.float64
type(f2) = numpy.ndarray
f2.shape = (1,)
对于numpy 1.9,这将提供:

np.array([f1,f2]) = [1.234, np.array([1.234])]
np.array([f1,f2]).dtype = numpy.float64
np.array([f1,f2]) = [1.234, np.array([1.234])]
np.array([f1,f2]).dtype = numpy.object
对于numpy 1.20,这将提供:

np.array([f1,f2]) = [1.234, np.array([1.234])]
np.array([f1,f2]).dtype = numpy.float64
np.array([f1,f2]) = [1.234, np.array([1.234])]
np.array([f1,f2]).dtype = numpy.object
而这是不被scipy.integrate.odeint所接受的。 但是,请注意,
scipy.integrate.solve\u ivp
对此没有问题


谢谢你的帮助

在运行
scipy.integrate.odeint
时,Numpy被告知将Python对象数组转换为浮点数组,它回答您它不能这样做。您的描述表明问题出在
y\u start
t\u start
或(可能,我不确定)
growth\u derivs的返回值上。请确保所有这些都具有适当的
dtype
,可以将其转换为浮点数。可能很容易修复。

感谢@RFoxtea提供了正确的解决方案

然而,有一个有趣的选择。您可以使用而不是
scipy.integrate.odeint


Solve_ivp可以处理
fun
的输出,即使用dtype
object

Ok,因此我更新了问题,添加了
y_start
t_start
,使用良好的dtype。但经济增长率并不高。这最终是因为numpy版本的变化。谢谢