In this Python tutorial, we will learn how to filter the NumPy array in Python. Also, we will cover these topics.
- Python NumPy filter two-dimensional array by condition
- Python NumPy filter 2d array
- Python NumPy filter values
- Python NumPy filter columns
- Python NumPy filter nan
- Python NumPy median filter
- Python NumPy gaussian filter
- Python NumPy low pass filter
- Python NumPy average filter
- Python NumPy butterworth filter
Python NumPy filter
- In this section, we will discuss how to filter the element in the NumPy array by using Python.
- In Python, the filter is used to get some values from the given array and then return a new array. To perform this particular task we are going to use the from.iter() method.
- In Python, the fromiter() method is used to create an array by taking iterable objects.
Syntax:
Here is the Syntax of numpy.fromiter() method
numpy.fromiter
(
iterable,
dtype,
count=-1
)
- It consists of a few parameters
- iterable: This parameter indicates the iterable objects.
- dtype: It specifies the data type of the input array.
- count: By default its values is -1 and it represents the numbers of times to read from buffer.
Example:
Let’s take an example and check how to filter the array in NumPy Python
import numpy as np
new_arr = np.array([16, 20, 12, 10, 8, 22, 97, 75, 43])
print("Creation of array:",new_arr)
final_output = np.fromiter((i for i in new_arr if i < 25), dtype = new_arr.dtype)
print("Filtering array:",final_output)
In the above Program, we initialized an array by using np.array() and then iterate over the array and filter out the values.
In this method, we have set the condition ‘i’ as less than 25. If the given array has less than 25 values then it filters those values and stores them into a new list.
Here is the implementation of the following given code
Read Python NumPy Delete
Python NumPy filter two-dimensional array by condition
- In this Program, we will discuss how to filter a two-dimensional Numpy array in Python.
- In this example, we are going to use the np.1d() function. In Python, the np.in1d() function takes two numpy arrays and it will check the condition whether the first array contains the second array elements or not.
- In Python, the np.1d() function always returns a boolean array.
- Now let’s have a look at the Syntax and understand the working of np.in1d() function.
import numpy as np
new_arr = np.array([[14,'m'],[16,'n'],[17,'o'],[21,'p']])
new_val = np.array(['n','o'])
result = np.in1d(new_arr[:, 1], new_val)
z=new_arr[result]
print("Filter 2-dimensional array:",z)
In the above code, we imported the numpy library and then use the np.array() function for creating an array.
After that, we have declared the variable ‘result’ and stored the np.in1d() function for intersecting both the arrays. Once you will print ‘z’ then the output will display the filter values from a given array.
Here is the Screenshot of the following given code
Python NumPy filter 2d array
- In this section, we will discuss how to filter a 2-dimensional NumPy array in Python.
- By using the np.any() function we can solve this problem. In Python the np.any() function is used on an array and it will check the condition if the input values are true.
Syntax:
Here is the Syntax of np.any() method
numpy.any
(
a,
axis=None,
out=None,
keepdims=<no value>,
*,
where=<no value>
)
Example:
Let’s take an example and check how to filter a 2-dimensional array in Python
import numpy as np
new_arr = np.array([[14,'m'],[16,'n'],[17,'o'],[21,'p']])
new_val = np.array(['n','o'])
d= new_arr[(new_arr[:,1,None] == new_val[None,:]).any(axis=1)]
print(d)
Here is the implementation of the following given code
Read Python NumPy Minimum tutorial
Python NumPy filter values
- Here we can see how to filter the values in the NumPy array by using Python.
- To perform this particular task we are going to apply the array condition method and it will help the user to get the filter values from a given array.
- In this example, we created a NumPy array by using the np.arange() function. After that, we have declared a varaible ‘result’ and stored the array condition into it. Once you will print ‘result’ then the output displays the values which are greater than 5.
Source Code:
import numpy as np
new_arr= np.arange(12).reshape(3,4)
result = new_arr[new_arr > 5]
print("Filter values from array:",result)
You can refer to the below Screenshot
Python NumPy filter columns
- In this section, we will discuss how to filter the columns in the NumPy array Python.
- By using the slicing() method we can solve this problem. In this example, we have created two arrays ‘new_arr’ and new_val’. In the first array, we have added only boolean values that represent the column values.
- It will check the condition if it is True then the column value will filter otherwise it will remove from the array.
Example:
Let’s take an example and understand how to filter only column values in the NumPy array
Source Code:
import numpy as np
new_arr = np.array([True, False, False])
new_val = np.array([[ 14, 26, 87 ],
[ 87, 65, 46 ]])
result=new_val[:, new_arr]
print(result)
Here is the execution of the following given code
As you can see in the Screenshot the output displays the updated array
Read Python NumPy Stack with Examples
Python NumPy filter nan
- In this section, we will discuss how to filter nan values in NumPy Python.
- To perform this particular task we are going to use the isnan() function. In Python, the isnan() function is used for removing nan values in the given array. This method will check the condition in an array, whether it contains nan value or not.
- In Python, the nan is a floating-point value and it is defined as not a number(Nan). This method will always return a NumPy array as a result that stores only boolean values.
Let’s have a look at the Syntax and understand the working of the isnan() function
numpy.isnan
(
x,
/,
out=None,
*,
where=True,
casting='same_kind',
orders='K',
dtype=None,
subok=True
[,
signature,
extobj
]
)
Example:
import numpy as np
new_arr = np.array([67, 124, np.nan, 654,np.nan,np.nan])
result = new_arr[np.logical_not(np.isnan(new_arr))]
print("Filter nan values:",result)
In the above code, we imported the numpy library and then initialize an array by using the np.array() function that contains three nan and three integer values. After that, we declared a variable ‘result’ and assigned the np.logical_not() function.
This function will help the user to convert the false value into true. So for nan values, the value will be ‘False’, and within this function, we have applied the np.isnan() function as an argument and it will return only integer values.
Here is the implementation of the following given code
Read Python NumPy round + 13 Examples
Python NumPy median filter
- In Python, the median filter is used for image manipulation and it will remove the pixel intensity of the central pixel part.
- In Python the median filter does not deal with speckle noise it works only the specified edge of an image and it also measures the pixel values of a given image.
- To perform this particular task we are going to use the concept of scipy.ndimage and it is a package that stores the number of image processing and functions. In Python image processing is like performing some operation on a particular image.
- In this Program, we imported two modules ‘NumPy’ and ‘scipy.ndimage’ for filtering the array. After that, we initialized an array by using the np.arange() function along with reshape(). Now use the scipy.ndimage.median_filter() function and pass the size keyword as an argument for converting into a new array.
Syntax:
Here is the Syntax of scipy.ndimage.median_filter() method
scipy.ndimage.median_filter
(
input,
size=None,
footprint=None,
output=None,
mode='reflect',
cval=0.0,
origin=0
)
Example:
import numpy as np
import scipy.ndimage
new_arr= np.ones((7, 7))
new_arr[1:6, 1:6] = np.arange(5*5).reshape((5, 5))
cent_out_val = scipy.ndimage.median_filter(new_arr, size=(5, 5))
right_out_val = scipy.ndimage.median_filter(new_arr, size=(5, 5), origin=(0, 1))
left_out_val = scipy.ndimage.median_filter(new_arr, size=(5, 5), origin=(0, -1))
print("Creation one-dimensional array:",new_arr)
print("Centered output for array:",cent_out_val)
print("Right output for array:",right_out_val)
print("Left output for array:", left_out_val)
Here is the Screenshot of the following given code
As you can see in the Screenshot the output displays the filtered array
Read Python Numpy unique
Python NumPy gaussian filter
- In this section, we will discuss how to use gaussian filter() in NumPy array Python.
- To do this task we are going to use the concept gaussian_filter(). In Python gaussian_filter() is used for blurring the region of an image and removing noise.
Syntax:
Here is the Syntax of scipy.ndimage.gaussian_filter() method
Scipy.ndimage.gaussian_filter
(
input,
sigma,
order=0,
output=None,
mode='reflect',
cval=0.0,
truncate=4.0
)
- It consists of a few parameters
- input: This parameter indicates the input array which we want to filter out.
- sigma: It specifies the standard deviation of the gaussian kernel and by default it takes only single integer number.
- order: This parameter order the filter along with each axis.
- Output: By default it takes ‘None’ value and it will be consider as input.
Example:
from scipy.ndimage import gaussian_filter
import numpy as np
new_arr = np.array([[ 12, 14, 16, 18, 20],
[22, 24, 26, 28, 30],
[32, 34, 36, 38, 40],
[42, 44, 46, 48, 50],
[52, 54, 56, 58, 60]])
print("Creation of array:",new_arr)
z= gaussian_filter(new_arr, sigma=1)
print("Gaussian filter:",z)
In the above code we imported two modules gaussian_filter() and numpy. After that we initialized an array by using np.array() method and assign integer values. Now use the gaussian_filter() function and pass ‘sigma=1’ as an argument.
You can refer to the below Screenshot
Read Python NumPy repeat
Python NumPy low pass filter
- In Python, to delete the frequencies in a signal of data we can easily use the concept of a low-Pass filter.
- In this Program, we imported the matplotlib library for plotting the filtered signal. To do this task first we declare a multiple varaible that indicates the frequency of sample rate as well as filter frequency cutoff.
- Now use the scipy.signal.lfilter() method and it filter the data along with one dimension.
Syntax:
Now let’s take a look at the Syntax and understand the working of the scipy.signal.filter() method
scipy.signal.lfilter
(
b,
a,
x,
axis=-1,
zi=None
)
Example:
Let’s take an example and check how to set a low-pass filter in an array by using NumPy Python
import numpy as np
from scipy import signal
import scipy
import matplotlib.pyplot as plt
i = 6
#frequency of sample rate
z = 35
#filter frequency cutoff
u = 2
#filter time second
m = 5
#total number of samples
new_val = z * m
time = np.linspace(0, m, new_val, endpoint=False)
signal = np.sin(2*np.pi*time) + 0.5*np.cos(6*2*np.pi*time) + 1.5*np.sin(9*2*np.pi*time)
p = 2 * u / z
q, r = scipy.signal.butter(i, p)
y_sig = scipy.signal.lfilter(q, r, signal)
plt.plot(time, signal, 'b-', label='signal')
plt.plot(time, y_sig, 'g-', linewidth=2, label='filtered signal')
plt.legend()
plt.show()
Here is the execution of the following given code
You can refer to the below Screenshot for graph
Python NumPy average filter
- In this session we will discuss how to filter the average value in NumPy Python.
- In this example, we will define the function ‘moving_average’ and then use the numpy.convolve() function for calculating the moving average of numpy array and it is also often seen in signal processing.
- This method takes three parameters and always return the discrete linear convolution of arrays.
Syntax:
Here is the Syntax of numpy.convolve() method
numpy.convolve
(
a,
v,
mode='full'
)
Example:
import numpy as np
def moving_average(y, v):
return np.convolve(y, np.ones(v), 'valid') / v
new_val = np.array([14,23,65,25,94,73,8,11,14,17,9,7])
print("Average filter:",moving_average(new_val,4))
Here is the Screenshot of the following given code
Python NumPy butterworth filter
- In this Program, we will discuss how to get the Butterworth filter in NumPy Python.
- In Python the butterworth is used for signal processing filter and it is design the filter and observe the magnitude.
- In this example we will use the concept of np.linspace() function and it is used for creating numeric values. After that we have applied the np.sin() method for getting the frequency range.
Source Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
new_arr = np.linspace(0,1,2000)
new_freq = np.sin(3*np.pi*200*new_arr)
plt.plot(new_freq)
new_freq2 = np.sin(4*np.pi*40*new_arr)
plt.plot(new_freq2)
result = new_freq + new_freq2
plt.plot(result)
plt.show()
You can refer to the below Screenshot
Here is the Screenshot of the Butterworth graph
Related Python NumPy tutorials:
- Python NumPy Split + 11 Examples
- Python NumPy Normalize
- Python NumPy Random [30 Examples]
- Python NumPy max
- Python NumPy shape with examples
In this Python tutorial, we will learn how to filter the NumPy array in Python. Also, we will cover these topics.
- Python NumPy filter two-dimensional array by condition
- Python NumPy filter 2d array
- Python NumPy filter values
- Python NumPy filter columns
- Python NumPy filter nan
- Python NumPy median filter
- Python NumPy gaussian filter
- Python NumPy low pass filter
- Python NumPy average filter
- Python NumPy butterworth filter
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.