In this article, we are going to see how to set the axis for rows and columns in NumPy.
Functions Used
- np.array(object): to create a NumPy array, the object is the parameter that contains the array
- np.reshape(rows, columns): to reshape the array into the specified number of rows and columns. Here in the below examples, we have given -1 in place of rows to let numpy figure it out if there are 3 columns in each row.
- np.sum(axis): to calculate the sum or addition of the elements. Here we have mentioned the axis to do the operation array-wise, row-wise, or column-wise as per requirement.
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:
Python3
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:
Python3
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:
Python3
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]