Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

python - how can I flatten an 2d numpy array, which has different length in the second axis?

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])

My Question is:

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])?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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])

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])

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's answer also has you covered for further information as to why you cannot use flatten() or ravel() given your array type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...