import numpy as np
Let us create an array in numpy
n = np.array([10,11,12,14])
np.where(condition, x, y)
Above syntax means, if condition is true, output is x otherwise y.
np.where(n < 11, 1, 0)
As we see, only number 10 is less than 11 and thats why we got first 1 and rest all zeros.
np.where((n >11) & (n <14),1,0)
n1 = np.arange(8)
n1
Let us replace the values less than 4 by -1.
np.where(n1 < 4,-1,n1)
Above command means if number is less than 4, replace it by -1 otherwise keep it same.
np.where can be used on Matrix too.
n2 = np.arange(9).reshape(3,3)
n2
np.where(n2 < 7,0,n2)
Above command makes everything 0 if number is less than 7.
n2
np.where((n2 >4) & (n2 < 8),0,n2)
All the values between 4 and 8 are 0.
Without the condition, np.where returns indices of places where the condition is true.
np.where((n2 >4) & (n2 < 8))
The above result means, value at index 1,2 (row1, col2) which is 5 satisfies the condition. Similarly values at other places 2,2 and 2,1 also satisfy the conditon.
Related Notebooks
- Numpy Basics
- Polynomial Interpolation Using Python Pandas Numpy And Sklearn
- Covid 19 Curve Fit Using Python Pandas And Numpy
- Numpy Array vs Vector
- Understand Tensors With Numpy
- How To Solve Error Numpy Has No Attribute Float In Python
- How To Handle nan In Numpy
- Convert Pandas DataFrame To Numpy Arrays
- How to do SQL Select and Where Using Python Pandas