将类型化的numpy数组列表转换为2d nump数组还是2d列表?

时间:2019-07-08 15:29:50

标签: python numpy numpy-ndarray

我有一个包含类型(float32)numpy数组的列表: list = [array([ 0.02741675, -0.23331268, -0.04920139, 0.2501195 ], dtype=float32), array([ 0.1675, -0.268, -0.139, 0.195 ], dtype=float32)]

我想将其转换为2d numpy数组。像这样:

array([[ 0.02741675, -0.23331268, -0.04920139, 0.2501195 ],[ 0.1675, -0.268, -0.139, 0.195 ]], dtype=float32)

我尝试做numpy.array(list),就像该网站上类似问题的答案所示,但它并没有改变,我怀疑是因为键入了numpy数组。如何做到这一点?

1 个答案:

答案 0 :(得分:2)

typing与它无关。所有的numpy数组都有一个dtype,即使打印显示中没有显示它也是如此。

通过显示重新创建列表:

In [428]: alist = [np.array([ 0.02741675, -0.23331268, -0.04920139,  0.2501195 ]), np.array([ 0.1675, -0.268,
     ...:  -0.139,  0.195 ])]                                                                                
In [429]: alist                                                                                              
Out[429]: 
[array([ 0.02741675, -0.23331268, -0.04920139,  0.2501195 ]),
 array([ 0.1675, -0.268 , -0.139 ,  0.195 ])]

正如一些评论所指出的,将np.array应用于列表会创建一个2d数组:

In [430]: np.array(alist)                                                                                    
Out[430]: 
array([[ 0.02741675, -0.23331268, -0.04920139,  0.2501195 ],
       [ 0.1675    , -0.268     , -0.139     ,  0.195     ]])

np.stack也是一样。

In [431]: np.stack(alist)                                                                                    
Out[431]: 
array([[ 0.02741675, -0.23331268, -0.04920139,  0.2501195 ],
       [ 0.1675    , -0.268     , -0.139     ,  0.195     ]])

有时人们从对象的dtype数组开始。在这种情况下,stack会在np.array无效的情况下起作用。

但是,如果列表中的数组形状不同,则两者都不起作用。

In [432]: alist = [np.array([ 0.02741675, -0.23331268, -0.04920139,  0.2501195 ]), np.array([ 0.1675, -0.268,
     ...:  -0.139])]          # remove an element                                                                               
In [433]: np.array(alist)                                                                                    
Out[433]: 
array([array([ 0.02741675, -0.23331268, -0.04920139,  0.2501195 ]),
       array([ 0.1675, -0.268 , -0.139 ])], dtype=object)
In [434]: np.stack(alist)                                                                                    
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-434-724d9c1d0554> in <module>
----> 1 np.stack(alist)

/usr/local/lib/python3.6/dist-packages/numpy/core/shape_base.py in stack(arrays, axis, out)
    414     shapes = {arr.shape for arr in arrays}
    415     if len(shapes) != 1:
--> 416         raise ValueError('all input arrays must have the same shape')
    417 
    418     result_ndim = arrays[0].ndim + 1

ValueError: all input arrays must have the same shape
相关问题