繁体   English   中英

从现有ndarray创建numpy ndarray

[英]creating numpy ndarrays from existing ndarrays

当我创建一个numpy数组时,形状通常会与我预期的形状不同。 我不知道自己要怎么做,请指出正确的方向。

例如:

theta = np.random.rand(n , 1)*2 *np.pi 
theta.round(3)
Out[283]: 
array([[ 0.827],
       [ 0.951],
       [ 5.371],
       [ 0.889]])

我想从theta创建一个带有矢量分量的数组(nx2数组)...我尝试了几次,但是总是得到错误的形状,如果我将其重塑就可以了,但是我当然应该能够直达那里。

速度= x和y的数组,其中x = v * cos(theta),y = v * sin(theta)

velocity.reshape(n, 2)
Out[281]: 
array([[ 1.16966072, -0.22284058],
       [-0.35621286,  0.7848923 ],
       [ 0.26813019, -1.17912768],
       [-1.14591116,  0.90771365]])

我尝试了几种构建数组的方法。 显然,我已经接近完成了,但是不太正确。

velocity = np.array((np.cos(theta) * v, np.sin(theta)*v), dtype=float)

velocity
Out[279]: 
array([[[ 1.16966072],
        [-0.22284058],
        [-0.35621286],
        [ 0.7848923 ]],

       [[ 0.26813019],
        [-1.17912768],
        [-1.14591116],
        [ 0.90771365]]])

velocity.shape
Out[280]: (2, 4, 1)

速度= np.array([[[np.cos(theta)* v],[np.sin(theta)* v]],dtype = float)

velocity
Out[274]: 
array([[[[ 1.16966072],
         [-0.22284058],
         [-0.35621286],
         [ 0.7848923 ]]],


       [[[ 0.26813019],
         [-1.17912768],
         [-1.14591116],
         [ 0.90771365]]]])

velocity.shape
Out[275]: (2, 1, 4, 1)


velocity = np.dstack((np.cos(theta) * v, np.sin(theta)*v))

velocity
Out[268]: 
array([[[ 1.16966072,  0.26813019]],

       [[-0.22284058, -1.17912768]],

       [[-0.35621286, -1.14591116]],

       [[ 0.7848923 ,  0.90771365]]])

velocity.shape
Out[269]: (4, 1, 2)

theta(n,1)

np.array([theta, theta])(2, n, 1) 也就是说, np.array沿着新轴将2个组成部分的数组连接np.arraynp.array将第2个组成为数组。

np.array([[theta], [theta]])将每个theta包装在[]中, so each is (1,n,1) , and together (2,1,n,1)`。

如果要(n,2),则需要在第二轴上串联。 例如:

velocity = np.concatenate([np.cos(theta) * v, np.sin(theta)*v], axis=1)

hstackcolumn_stack也将做到这一点,还有c_

如果将theta创建为(n,) (1d而不是2),则可能已使用stack将它们连接到新的第二轴上:

velocity = np.stack([np.cos(theta) * v, np.sin(theta)*v], axis=1)

np.array([...]).T ,即制作(2,n)并转置它。

有很多方法可以将两个n元素数组连接成一个(n,2)数组。 甚至np.squeeze(np.array(....)).T ,从(2,n,1)中删除1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM