Home »
Python »
Python Programs
How to perform function application over NumPy's matrix row/column?
Learn, how can we perform function application over NumPy's matrix row/column in Python?
Submitted by Pranit Sharma, on March 27, 2023
Suppose that we are given a numpy matrix and we need to apply a simple comparison function on this matrix in such a way that we can compute elements that lie in a range in a column or row.
NumPy Matrix - Function application over row/column
To perform function application over NumPy's matrix row/column, we can use different approaches. One can opt for numpy.vectorize() or numpy.frompyfunc() but they would not make the code run fast. Hence, we can simply use the basic numpy's indexing and compare the elements of the column or a row of this matrix and at the end, we can apply numpy.sum method to count all the elements that are passed by this condition.
Let us understand with the help of an example,
Python code to perform function application over NumPy's matrix row/column
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.random.randint(-4, 4, 40).reshape(8, 5)
# Display original data
print("Original data:\n",arr,"\n")
# Comparing the values of second column to
# check which values are greater than 2
res = arr[:,1] > 2
# Display result
print("Total values in second column which are greater than 2:\n",np.sum(res),"\n")
# Comparing the values of last column to
# check which vlaues are less than 0
res = arr[:,-1] > 0
# Display result
print("Total values in last column which are less than 0:\n",np.sum(res),"\n")
Output
Original data:
[[-4 2 3 1 3]
[-2 -1 3 -3 3]
[ 1 0 -4 2 -4]
[-1 -4 2 -1 -4]
[ 2 2 1 -1 1]
[-1 0 3 0 1]
[ 0 0 -4 -2 1]
[ 2 -3 -2 -3 2]]
Total values in second column which are greater than 2:
0
Total values in last column which are less than 0:
6
Python NumPy Programs »