分裂在Python数组 [英] splitting an array in Python

查看:230
本文介绍了分裂在Python数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,它是(219812,2),但我需要分裂 2(219812)

我不断收到错误 ValueError错误:操作数无法与形状(219812,2)(219812)

一起播出

我怎样才能做到?

正如你所看到的,我需要从u = odeint,多带他们两个独立的解决方案。

 高清DERIV(U,T):
    返回的数组([U [1],U [0] - np.sqrt(U [0])])时间= np.arange(0.01,7 * np.pi,0.0001)
uinit =阵列([1.49907,0])
U = odeint(DERIV,uinit,时间)X = 1 / U * np.cos(时间)
Y = 1 / U * np.sin(时间)积(X,Y)
plt.show()


解决方案

要提取二维数组的第i列,使用改编[:,我]

您也可以解压阵列(它的工作原理排明智的,所以你需要转 U 使之具有形状(2,N)),使用 U1,U2 = UT

顺便说一句,星进口并不大(可能除了在终端交互使用),所以我增加了几个 NP的。 PLT 到code,它变为:

 高清DERIV(U,T):
    返回np.array([U [1],U [0] - np.sqrt(U [0])])时间= np.arange(0.01,7 * np.pi,0.0001)
uinit = np.array([1.49907,0])
U = odeint(DERIV,uinit,时间)X = 1 / U [:,0] * np.cos(时间)
Y = 1 / U [:, 1] * np.sin(时间)plt.plot(X,Y​​)
plt.show()

这也似乎是一个对数图看起来更好。

I have an array that is (219812,2) but I need to split to 2 (219812).

I keep getting the error ValueError: operands could not be broadcast together with shapes (219812,2) (219812)

How can I accomplish?

As you can see, I need to take the two separate solutions from u = odeint and multiple them.

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()

解决方案

To extract the ith column of a 2D array, use arr[:, i].

You could also unpack the array (it works row wise, so you need to transpose u so that it has shape (2, n)), using u1, u2 = u.T.

By the way, star imports aren't great (except maybe in the terminal for interactive use), so I added a couple of np. and plt. to your code, which becomes:

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()

It also seems like a logarithmic plot looks nicer.

这篇关于分裂在Python数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆