我怎么能压扁的二维数组numpy的,它在第二轴的长度不同? [英] how can I flatten an 2d numpy array, which has different length in the second axis?

查看:1057
本文介绍了我怎么能压扁的二维数组numpy的,它在第二轴的长度不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy的阵列,它看起来像:

I have a numpy array which looks like:

myArray = np.array([[1,2],[3]])

但我不能将其压平,

But I can not flatten it,

In: myArray.flatten()
Out: array([[1, 2], [3]], dtype=object)

如果我改变数组中的第二个轴的长度相同,那么我可以将其压平。

If I change the array to the same length in the second axis, then I can flatten it.

In: myArray2 = np.array([[1,2],[3,4]])
In: myArray2.flatten()
Out: array([1, 2, 3, 4])

我的问题是:

我可以使用像 myArray.flatten()不管阵列的尺寸和元素的长度,得到输出一些事情:阵列([1,2,3])

Can I use some thing like myArray.flatten() regardless the dimension of the array and the length of its elements, and get the output: array([1,2,3])?

推荐答案

myArray的对象的一维数组的。您的列表对象将只保持与相同的顺序压扁()拉威尔()。您可以使用 hstack 以水平堆叠顺序数组:

myArray is a 1-dimensional array of objects. Your list objects will simply remain in the same order with flatten() or ravel(). You can use hstack to stack the arrays in sequence horizontally:

>>> np.hstack(myArray)
array([1, 2, 3])

请注意,这基本上等同于使用 CONCATENATE 为1的轴(这应该是有意义直观的):

Note that this is basically equivalent to using concatenate with an axis of 1 (this should make sense intuitively):

>>> np.concatenate(myArray, axis=1)
array([1, 2, 3])

如果您的的但是有这个问题,的可以的合并项目,它总是preferable使用压扁() 拉威尔()性能:

If you don't have this issue however and can merge the items, it is always preferable to use flatten() or ravel() for performance:

In [1]: u = timeit.Timer('np.hstack(np.array([[1,2],[3,4]]))'\
   ....: , setup = 'import numpy as np')
In [2]: print u.timeit()
11.0124390125

In [3]: u = timeit.Timer('np.array([[1,2],[3,4]]).flatten()'\
   ....: , setup = 'import numpy as np')
In [4]: print u.timeit()
3.05757689476

Iluengo的回答也有你覆盖了更多的信息,为什么你不能使用压扁( )拉威尔()给您的数组类型。

Iluengo's answer also has you covered for further information as to why you cannot use flatten() or ravel() given your array type.

这篇关于我怎么能压扁的二维数组numpy的,它在第二轴的长度不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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