Saras Arya Saras Arya - 6 days ago 6
Python Question

How to reshape numpy array of array into single row

I have a numpy array as

[[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
...,
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]]


I would like to have it as

0
0
0
.
.
0
0


I know that we have to use the reshape function, but how to use it, is I am not able to figure out,

my attempt

np.reshape(new_arr, newshape=1)


Which gives an error

ValueError: total size of new array must be unchanged


The documentation isn't very friendly

Answer

You can also have a look at numpy.ndarray.flatten:

a = np.array([[1,2], [3,4]])
a.flatten()

# array([1, 2, 3, 4])

The difference between flatten and ravel is that flatten will return a copy of the array whereas ravel will refence the original if possible. Thus, if you modify the array returned by ravel, it may also modify the entries in the original array.

It is usually safer to create a copy of the original array, although it will take more time since it has to allocate new memory to create it.

You can read more about the difference between these two options here.

Comments