如何在Python中将数组数组转换为多维数组? [英] How do I convert an array of arrays into a multi-dimensional array in Python?

查看:292
本文介绍了如何在Python中将数组数组转换为多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a NumPy array (of length X) of arrays, all of which are of the same length (Y), but which has type "object" and thus has dimension (X,). I would like to "convert" this into an array of dimension (X, Y) with the type of the elements of the member arrays ("float").

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

The only way I can see to do this is "manually" with something like

[x for x in my_array]

是否有更好的成语来完成这种转换"?

Is there a better idiom for accomplishing this "conversion"?

例如,我有类似的东西:

For example I have something like:

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)

具有shape(X,)而不是(X,10)的

.

which has shape (X,) rather than (X, 10).

推荐答案

您可以在新轴上串联数组.例如:

You can concatenate the arrays on a new axis. For example:

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

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

To make an array of arrays we can't just combine them with array, as the deleted answer did:

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)

相反,我们必须创建一个形状正确的空数组,并将其填充:

Instead we have to create an empty array of the right shape, and fill it:

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)

np.stack的行为与np.array相似,但使用的是concatenate:

np.stack acts like np.array, but uses 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.]])

我们还可以使用concatenatehstackvstack组合不同轴上的数组.他们都将数组数组视为数组列表.

We could also use concatenate, hstack or vstack to combine the arrays on different axes. They all treat the array of arrays as a list of arrays.

如果arr是2d(或更高),我们必须先ravel.

If arr is 2d (or higher) we have to ravel it first.

这篇关于如何在Python中将数组数组转换为多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆