How do I use numpy.newaxis with NumPy array?

In this tutorial, we will learn how to use numpy.newaxis with NumPy array? By Pranit Sharma Last updated : May 24, 2023

numpy.newaxis

The numpy.newaxis is an alias for None, useful for indexing arrays. The numpy.newaxis is used to increase the dimension of the existing array by one more dimension.

numpy.newaxis Syntax

numpy.newaxis

Let us understand with the help of an example,

Example of numpy.newaxis with NumPy array in Python

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([0, 1, 2, 3])

# Display original array
print("Orignal array:\n",arr,"\n")

# New axis
res = arr[np.newaxis, :]
# Display Result
print("Result 1:\n",res,"\n")

res = arr[:, np.newaxis, np.newaxis]
# Display Result
print("Result 2:\n",res,"\n")

res = arr[:, np.newaxis] * arr
# Display Result
print("Result 3:\n",res,"\n")

Output

The output of the above program is:

Orignal array:
 [0 1 2 3] 

Result 1:
 [[0 1 2 3]] 

Result 2:
 [[[0]]

 [[1]]

 [[2]]

 [[3]]] 

Result 3:
 [[0 0 0 0]
 [0 1 2 3]
 [0 2 4 6]
 [0 3 6 9]] 

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.