Let’s learn how to reshape to automatic value of dimension in Numpy Python library.
Why you need the trick
You may need this trick when:
The trick is:
put -1 as a value!
How to do the trick
See the example code:
import numpy as np my_array = np.random.random([6, 6]) print(f'The original array: \n {my_array}') reshaped_array = my_array.reshape(2, -1, 3) print(f'The modified array: \n {reshaped_array}')
As you can see I put reshape(2, -1, 3) and it worked. Numpy automatically guessed that it should be 6 instead of -1.
Remember: you can use -1 only once!
When to use the trick
You can use the `-1` value to automatically resize Numpy arrays in the following cases:
When you don’t know the size of the base array.
When you expect the base array to change size.
When you don’t know which value of dimension to put.