Open In App

How to Set Axis for Rows and Columns in NumPy ?

In this article, we are going to see how to set the axis for rows and columns in NumPy.

Functions Used

Example 1: Set axis for array-wise calculation



In this example, we will reshape the NumPy array into rows having 3 columns each i.e nparray.reshape(-1, 3) to make it two-dimensional. Then we will perform the sum operation of the array elements array-wise that is in normal order starting from the first to last element of the NumPy array. We specifically set the axis= None to trigger the normal array-wise operation.

Code:






import numpy as np
nparray = np.array([[1, 2, 3], [11, 22, 33],
                    [4, 5, 6], [8, 9, 10],
                    [20, 30, 40]])
 
nparray = nparray.reshape(-1, 3)
print(nparray)
 
# calculating sum along
# axix=None i.e array-wise
output = nparray.sum(axis=None)
print("\n\nSum array-wise: ", output)

Output :

[[ 1  2  3]
 [11 22 33]
 [ 4  5  6]
 [ 8  9 10]
 [20 30 40]]


Sum array-wise:  204

Example 2: Set axis for column-wise calculation

In this example, we will reshape the numpy array into rows having 3 columns each. Then perform the sum operation of the array elements using the sum() function column-wise. We specifically set the axis= 0 to trigger the normal array-wise operation.

Code:




import numpy as np
 
 
nparray = np.array([[1, 2, 3], [11, 22, 33],
                    [4, 5, 6], [8, 9, 10],
                    [20, 30, 40]])
nparray = nparray.reshape(-1, 3)
print(nparray)
 
# calculating sum along axix=0
# i.e column-wise
output = nparray.sum(axis = 0)
print("\n\nSum column-wise: ", output)

Output :

[[ 1  2  3]
 [11 22 33]
 [ 4  5  6]
 [ 8  9 10]
 [20 30 40]]


Sum column-wise:  [44 68 92]

Example 3: Set axis for row-wise calculation

We will specifically set the axis = 1 to trigger the normal row-wise calculation.

Code:




import numpy as np
nparray = np.array([[1, 2, 3], [11, 22, 33],
                    [4, 5, 6], [8, 9, 10],
                    [20, 30, 40]])
 
nparray = nparray.reshape(-1, 3)
print(nparray)
 
# calculating sum along axix=1
# i.e row0wise
output = nparray.sum(axis = 1)
print("\n\nSum row-wise: ", output)

Output :

[[ 1  2  3]
 [11 22 33]
 [ 4  5  6]
 [ 8  9 10]
 [20 30 40]]


Sum row-wise:  [ 6 66 15 27 90]

Article Tags :