Categories: NumpyPython

How to filter values of Numpy array in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

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])

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

wilsonzhang746

Recent Posts

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

2 weeks ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

4 weeks ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

2 months ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

2 months ago

Download R Course source files

Click here to download R Course source files !

11 months ago

Download Python Course source files

Click here to download Python Course Source Files !

11 months ago