2013-04-11 119 views
1

我有一个数组是(219812,2),但我需要分割为2 (219812)在Python中分割数组

我不断收到错误ValueError: operands could not be broadcast together with shapes (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() 

回答

3

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

您也可以使用u1, u2 = u.T对数组进行解压缩(它的工作方式是明智的,所以您需要转置u以使其具有形状(2,n))。

顺便说一句,星进口并不大(可能除了在终端交互使用),所以我加了几个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() 

它还看起来像一个对数阴谋看起来更好。

+0

得到它的阴谋,但情节是错误的。 – dustin 2013-04-11 16:59:28

+1

@dustin确保你没有计算/绘制其他东西。这显示了如何“分割”一个数组,我认为这可以回答你的问题。没有更多信息,我们将无法帮助您解决您的其他问题。 – jorgeca 2013-04-11 17:15:41

+1

@dustin你想'plt.plot(time,u [:,0])'? – jorgeca 2013-04-11 17:31:57

1

这听起来像你想索引的元组:

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) 
+0

返回相同的错误我得到:'ValueError:操作数不能与形状一起广播(2)(219812)' – dustin 2013-04-11 15:58:02

+1

在原始帖子中提及该错误将是有用的。 – Amber 2013-04-11 16:01:50

1
u1,u2 = odeint(deriv, uinit, time) 

也许?

+0

我给出的错误'太多的值解包'与此。 – dustin 2013-04-11 16:01:44

+2

@dustin然后尝试'u1,u2 = odeint(deriv,uinit,time).T'。 – Jaime 2013-04-11 16:56:37