Example 1
The example shown below converts a 1-dimensional array into a 2D array as shown below:
arr = np.array([1, 2, 3, 4, 5])
print(arr)
new_arr = arr[np.newaxis]
print(new_arr)
The code above should convert the 1D array into a column matrix as shown below:
As mentioned, the newaxis method is very similar to using the None parameter as shown below:
arr = np.array([1, 2, 3, 4, 5])
print(arr)
new_arr = arr[None]
print(new_arr)
This returns a similar value as shown below:
Example 2
What happens when you apply the newaxis on a 2D array. Take a look at the example below:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
new_arr = arr[np.newaxis]
print(new_arr)
This should return a new array as shown:
Note that you can insert more than one axis as shown:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
new_arr = arr[np.newaxis, np.newaxis]
print(new_arr)
The above code should return:
Terminating
This short article illustrates various examples of using the np.newaxis object. Check the docs to learn more.