如何在 Python 中将数组数组转换为多维数组?

oro*_*ome 5 python arrays numpy data-conversion

我有一个数组的 NumPy 数组(长度为 X),所有数组的长度都相同(Y),但类型为“对象”,因此具有维度(X,)。我想将其“转换”为具有成员数组元素类型(“float”)的维度数组(X,Y)。

我能看到的唯一方法是“手动”使用类似的东西

[x for x in my_array]
Run Code Online (Sandbox Code Playgroud)

有没有更好的成语来完成这种“转换”?


例如我有类似的东西:

array([array([ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]),
       array([ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]),
       array([ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]), ...,
       array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.]),
       array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.]),
       array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.])], dtype=object)
Run Code Online (Sandbox Code Playgroud)

其中有shape(X,) 而不是 (X, 10)。

hpa*_*ulj 3

您可以将数组连接到新轴上。例如:

In [1]: a=np.array([1,2,3],dtype=object)
   ...: b=np.array([4,5,6],dtype=object)
Run Code Online (Sandbox Code Playgroud)

要创建数组数组array,我们不能像删除的答案那样将它们与 组合起来:

In [2]: l=np.array([a,b])
In [3]: l
Out[3]: 
array([[1, 2, 3],
       [4, 5, 6]], dtype=object)
In [4]: l.shape
Out[4]: (2, 3)
Run Code Online (Sandbox Code Playgroud)

相反,我们必须创建一个形状正确的空数组,然后填充它:

In [5]: arr = np.empty((2,), object)
In [6]: arr[:]=[a,b]
In [7]: arr
Out[7]: array([array([1, 2, 3], dtype=object), 
               array([4, 5, 6], dtype=object)], 
              dtype=object)
Run Code Online (Sandbox Code Playgroud)

np.stack行为类似np.array,但使用concatenate

In [8]: np.stack(arr)
Out[8]: 
array([[1, 2, 3],
       [4, 5, 6]], dtype=object)
In [9]: _.astype(float)
Out[9]: 
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])
Run Code Online (Sandbox Code Playgroud)

我们还可以使用concatenate,hstackvstack来组合不同轴上的数组。它们都将数组的数组视为数组的列表。

如果arr是 2d(或更高),我们必须ravel首先处理它。