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
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 .
According to the documentation :
np.reshape(new_arr, newshape=n*m)
where n
and m
are the number of rows and columns, respectively, of new_arr
Use the ravel()
method :
In [1]: arr = np.zeros((2, 2))
In [2]: arr
Out[2]:
array([[ 0., 0.],
[ 0., 0.]])
In [3]: arr.ravel()
Out[3]: array([ 0., 0., 0., 0.])
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.