0

I have an array

np.array([[[ 1,  2], [ 3, -4]],[[-1,  0]]], dtype=object)

and I want to flatten it to get something like:

array([1,2,3,-4,-1,0], dtype=int32)

I tried Flatten numpy array but it raises a Value error

To be clear, my array is always an object array consists of multiple 2D and 1D arrays

3 Answers3

1
In [333]: arr = np.array([[[ 1,  2], [ 3, -4]],[[-1,  0]]], dtype=object)                                       
In [334]: arr                                                                                                   
Out[334]: array([list([[1, 2], [3, -4]]), list([[-1, 0]])], dtype=object)
In [335]: arr.shape                                                                                             
Out[335]: (2,)
In [336]: np.vstack(arr)                                                                                        
Out[336]: 
array([[ 1,  2],
       [ 3, -4],
       [-1,  0]])
In [337]: np.vstack(arr).ravel()                                                                                
Out[337]: array([ 1,  2,  3, -4, -1,  0])
hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

If you dont know the depth of your nestet array you can do it like this:

l = np.array([[[ 1,  2],[ 3, -4]], [-1,  0]])

from collections.abc import Iterable

def flatten(l):
    returnlist=[]
    for elem in l:
        if isinstance(elem, Iterable):
            returnlist.extend(flatten(elem))
        else:
            returnlist.append(elem)

    return returnlist

np.array(flatten(l))

If its 2 dimensional you can go like that post suggest How to make a flat list out of list of lists:

flat_list = [item for sublist in l for item in sublist]

or just use numpys flatten.

By the way, your example is not two dimensional because of those double brackets, thats also why flatten() does not work:

np.array([[[ 1, 2], [ 3, -4 ]],[[-1, 0]]], dtype=object)

Florian H
  • 3,052
  • 2
  • 14
  • 25
0

It's nested, but you can use sum() to do this:

nested_list_values = [[[ 1,  2], [ 3, -4]],[[-1,  0]]]
sum(sum(, []), [])

[1, 2, 3, -4, -1, 0]

Or, with itertools.chain() if that feels more natural:

from itertools import chain

nested_list_values = [[[ 1,  2], [ 3, -4]],[[-1,  0]]]
list(chain(*chain(*nested_list_values)))

[1, 2, 3, -4, -1, 0]

monkut
  • 42,176
  • 24
  • 124
  • 155