首页 > 解决方案 > numpy 形状与数组结构不一致

问题描述

我要为这件事发疯了。

我有 2 个清单

A = [ [[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3],[1,2,3]]]
B = [ [[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3]]]

当我将 A 和 B 的形状称为 numpy 数组时,我得到了这个:

In [33]: np.asarray(A).shape
Out[33]: (2, 3, 3)

In [31]: np.asarray(B).shape
Out[31]: (2,)

我如何A以相同的方式塑造B,即(2,)

我想我明白为什么会发生这种情况,但我不知道如何防止这种情况发生。请问有人有什么帮助/想法吗?

谢谢!

标签: arrayslistnumpyobjectshapes

解决方案


您的 2 个列表:

In [232]: A
Out[232]: [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]
In [233]: B
Out[233]: [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]]

现在,解释为什么B结果比那个更好A

In [234]: np.array(A)
Out[234]: 
array([[[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]],

       [[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]]])

In [235]: np.array(B)
<ipython-input-235-c938532b77c1>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  np.array(B)
Out[235]: 
array([list([[1, 2, 3], [1, 2, 3], [1, 2, 3]]),
       list([[1, 2, 3], [1, 2, 3]])], dtype=object)

推荐阅读