Home > other >  Why doesn't numpy flatten() work after converting a nested list into an array?
Why doesn't numpy flatten() work after converting a nested list into an array?

Time:07-19

I created a nested list and converted both the inner lists and the whole list into a numpy array, but numpy flatten() failed to flatten the final array.

a = [1]
b = [2, 3]
c = [4, 5, 6]
d = [7, 8]
e = [9]
lst = [a, b, c, d, e]
arr = np.array([np.array(l) for l in lst], dtype='object')
print(type(arr))
print(arr.flatten())

I got the following output:

<class 'numpy.ndarray'>
[array([1]) array([2, 3]) array([4, 5, 6]) array([7, 8]) array([9])]

expected output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

CodePudding user response:

You got ndarray of ndarrays, which is not 2d array.

Also, ndarray should have same size for all rows.

CodePudding user response:

You can use list.extend.

arr = []
for l in lst:
    # Or as alternative -> arr  = l
    arr.extend(l)
arr = np.array(arr)
print(arr)
print(type(arr))

[1 2 3 4 5 6 7 8 9]
<class 'numpy.ndarray'>

CodePudding user response:

You should flatten it properly, and then make a nd array. Like this:

arr = np.array([j for i in lst for j in i], dtype='object')
  • Related