且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将numpy数组转换为2d数组

更新时间:2022-11-09 23:28:14

在回答您的评论问题时,让我们比较两种创建数组的方法

In response your comment question, let's compare 2 ways of creating an array

首先从数组列表(长度相同)中创建一个数组:

First make an array from a list of arrays (all same length):

In [302]: arr = np.array([np.arange(3), np.arange(1,4), np.arange(10,13)])
In [303]: arr
Out[303]: 
array([[ 0,  1,  2],
       [ 1,  2,  3],
       [10, 11, 12]])

结果是二维数组.

相反,如果我们创建一个对象dtype数组,并用数组填充它:

If instead we make an object dtype array, and fill it with arrays:

In [304]: arr = np.empty(3,object)
In [305]: arr[:] = [np.arange(3), np.arange(1,4), np.arange(10,13)]
In [306]: arr
Out[306]: 
array([array([0, 1, 2]), array([1, 2, 3]), array([10, 11, 12])],
      dtype=object)

请注意,此显示与您的显示类似.通过设计,这是一维数组.像列表一样,它包含指向内存中其他位置的数组的指针.请注意,这需要额外的构造步骤. np.array的默认行为是在可以的地方创建一个多维数组.

Notice that this display is like yours. This is, by design a 1d array. Like a list it contains pointers to arrays elsewhere in memory. Notice that it requires an extra construction step. The default behavior of np.array is to create a multidimensional array where it can.

要解决这个问题需要花费额外的精力.同样,要撤消该操作也需要付出额外的努力-创建2d数字数组.

It takes extra effort to get around that. Likewise it takes some extra effort to undo that - to create the 2d numeric array.

仅在其上调用np.array不会更改结构.

Simply calling np.array on it does not change the structure.

In [307]: np.array(arr)
Out[307]: 
array([array([0, 1, 2]), array([1, 2, 3]), array([10, 11, 12])],
      dtype=object)

stack确实将其更改为2d. stack将其视为数组列表,并在新轴上联接.

stack does change it to 2d. stack treats it as a list of arrays, which it joins on a new axis.

In [308]: np.stack(arr)
Out[308]: 
array([[ 0,  1,  2],
       [ 1,  2,  3],
       [10, 11, 12]])