0

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

1
  • 1
    np.reshape(new_arr, newshape=-1). The -1 lets numpy calculate the required shape. Commented Nov 28, 2016 at 17:53

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.])

Comments

0

We can use reshape function for same.

suppose we have an array

a = [[1, 2], [3, 4]]

total 4 elements are there. We can convert using following command

a.reshape(4)

[1, 2, 3, 4]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.