在Python中拆分数组

在Python中拆分数组,python,arrays,numpy,Python,Arrays,Numpy,我有一个数组是219812,2,但我需要拆分为219812 我一直得到错误值error:操作数无法与形状219812,2 219812一起广播 我怎样才能做到 如您所见,我需要从u=odeint中获取两个单独的解决方案,并将其多重化 def deriv(u, t): return array([ u[1], u[0] - np.sqrt(u[0]) ]) time = np.arange(0.01, 7 * np.pi, 0.0001) uinit = array([ 1.49907,

我有一个数组是219812,2,但我需要拆分为219812

我一直得到错误值error:操作数无法与形状219812,2 219812一起广播

我怎样才能做到

如您所见,我需要从u=odeint中获取两个单独的解决方案,并将其多重化

def deriv(u, t):
    return array([ u[1], u[0] - np.sqrt(u[0]) ])

time = np.arange(0.01, 7 * np.pi, 0.0001)
uinit = array([ 1.49907, 0])
u = odeint(deriv, uinit, time)

x = 1 / u * np.cos(time)
y = 1 / u * np.sin(time)

plot(x, y)
plt.show()

听起来像是要索引到元组中:

foo = (123, 456)
bar = foo[0] # sets bar to 123
baz = foo[1] # sets baz to 456
所以在你的情况下,听起来你想做的可能是

u = odeint(deriv, uinit, time)

x = 1 / u[0] * np.cos(time)
y = 1 / u[1] * np.sin(time)

听起来像是要索引到元组中:

foo = (123, 456)
bar = foo[0] # sets bar to 123
baz = foo[1] # sets baz to 456
所以在你的情况下,听起来你想做的可能是

u = odeint(deriv, uinit, time)

x = 1 / u[0] * np.cos(time)
y = 1 / u[1] * np.sin(time)
也许吧


可能?

要提取二维数组的第i列,请使用arr[:,i]

您还可以解压它按行工作的数组,因此您需要转置u,使其具有形状2,n,使用u1,u2=u.T

顺便说一句,除了在终端中进行交互使用外,star导入不是很好,所以我添加了几个np。和plt。添加到您的代码,这将成为:

def deriv(u, t):
    return np.array([ u[1], u[0] - np.sqrt(u[0]) ])

time = np.arange(0.01, 7 * np.pi, 0.0001)
uinit = np.array([ 1.49907, 0])
u = odeint(deriv, uinit, time)

x = 1 / u[:, 0] * np.cos(time)
y = 1 / u[:, 1] * np.sin(time)

plt.plot(x, y)
plt.show()

对数图看起来也更好。

要提取2D数组的第i列,请使用arr[:,i]

您还可以解压它按行工作的数组,因此您需要转置u,使其具有形状2,n,使用u1,u2=u.T

顺便说一句,除了在终端中进行交互使用外,star导入不是很好,所以我添加了几个np。和plt。添加到您的代码,这将成为:

def deriv(u, t):
    return np.array([ u[1], u[0] - np.sqrt(u[0]) ])

time = np.arange(0.01, 7 * np.pi, 0.0001)
uinit = np.array([ 1.49907, 0])
u = odeint(deriv, uinit, time)

x = 1 / u[:, 0] * np.cos(time)
y = 1 / u[:, 1] * np.sin(time)

plt.plot(x, y)
plt.show()

对数图看起来也更好。

返回了与我得到的相同错误:ValueError:操作数无法与形状2 219812一起广播在您的原始帖子中提及该错误会很有用。返回了与我得到的相同错误:ValueError:操作数无法与形状2一起广播219812在你原来的帖子中提到这个错误会很有用。@dustin然后试试u1,u2=odeintderiv,uinit,time.T。@dustin然后试试u1,u2=odeintderiv,uinit,time.T。@dustin确保你没有计算/绘制其他东西。这显示了如何拆分数组,我认为这回答了您的问题。如果没有更多信息,我们将无法帮助您解决其他问题。@dustin是否需要plt.plottime,u[:,0]?@dustin您的脚本可能还有一些其他问题,如果您有兴趣让它工作,您应该就您感兴趣解决的实际问题问另一个问题。我注意到的一件事是,你的deriv方程接受一个t参数,并且从不使用它。此外,它是按行而不是按列拆分数组。@askewchan这里有一个链接,指向另一种解决方法,但仍然没有运气。@dustin请确保您没有计算/绘制其他内容。这显示了如何拆分数组,我认为这回答了您的问题。如果没有更多信息,我们将无法帮助您解决其他问题。@dustin是否需要plt.plottime,u[:,0]?@dustin您的脚本可能还有一些其他问题,如果您有兴趣让它工作,您应该就您感兴趣解决的实际问题问另一个问题。我注意到的一件事是,你的deriv方程接受一个t参数,并且从不使用它。另外,它是按行而不是按列拆分数组。@askewchan这里有一个链接,指向另一种解决方法,但仍然不走运。