When a Numpy array is created, its values can be filtered, mainly via conditional tests statement. We provides several examples of filtering array in the following examples.
#Import Numpy module
import numpy as np
### Create an array of 9 elements
A = np.arange(0, 9)
A
#output
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
#filter array with values larger than 3, and store to a new array
A1 = A[A > 3]
A1
#output
array([4, 5, 6, 7, 8])
#Create a two-dimensional array of 9 elements
B = np.arange(0, 9).reshape(3,3)
B
#output
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
#filtering elements of larger than 3 and store to a new array
B1 = B[B > 3]
B1
#output
array([4, 5, 6, 7, 8])
#Selecting values larger than 2 and less than 7 from array
C1 = A[(A> 2) & (A< 7)]
C1
#output
array([3, 4, 5, 6])
#Selecting values less than 2 or larger than 7 from original array
#and store to a new array
D1 = A[(A< 2) | (A> 7)]
D1
#output
array([0, 1, 8])
Numpy provides also function in1d() which meets values in a list as filtering condition.
#Selecting values that inside the specified list
#and store to a new array
E1 = A1[np.in1d(A1, [4, 7, 32, 19,0.3])]
E1
#output
array([4, 7])
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…