简体   繁体   中英

How to make a linear data list from a numpy ndarray?

I would like to efficiently turn an ndarray into a linear list so I can easily pass it to my boost module and make the indexing calculations in C.

Basically I have an n-dimension ndarray, for example

>>> a = np.ndarray((2, 2, 2))

which would give me

array([[[ 0,   0],
        [  0,   0]],

       [[  0,   0],
        [  0,   0]]])

then I would do

a.serialize()
[0, 0, 0, 0, 0, 0, 0, 0]

How can I do that?

Try one of the following:

a.flatten() or a.ravel()

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html

What you are intending to do is called flattening an array which can be achieved by calling the flatten method. The end result can then be converted to a list. You can also unroll the array with the library level function numpy.ravel . As it is a library level function, it works for any object and not just ndarray. Also it only creates a copy if required where in flatten alays creates a copy.

>>> a = np.ndarray((2, 2, 2))
>>> a.flatten()
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>> list(a.flatten())
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

a.ravel() " unrolls " your array into a "flat" version of a . It creates a copy only if necessary, which is kind of a hazard -- sometimes, when changing a value, eg a.ravel()[4] = 3.141 , you only change a copy, and sometimes you change the original.

If what you need is really just an 1D-accessor, try a.flat , which will "just" translate 1D indices to the matching 2D indices:

 a = numpy.ndarray((2,2))
 a.flat[3] = 4
 print a[1,1]
 >>>4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM