Categories: PandasPython

How to filter a Pandas Series in Python

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

Series is a data structure type that stores one dimensional labeled data in Pandas module in Python. When a Series is created, its value can be filtered using loc() function, and the result can be stored into a new Series. Filtering conditional can be any of combination of conditional statements. isin() function can also be used to match specific values in filtering statement. Next code examples show implementation of these operations in Python IDE.

#Import Pandas and Numpy module
import pandas as pd
import numpy as np
#Create an array of 5 elements
T = np.array([32, 301, 19, 7, 13])
U = pd.Series(T)
U
#output
0     32
1    301
2     19
3      7
4     13
dtype: int32
#filtering value larger than 10 from Series and save to a new Series
R1 = U.loc[lambda x: x > 10]
R1
#output
0     32
1    301
2     19
4     13
dtype: int32
#Filtering values larger than 10 and smaller than 25
#result saved to a new Series
R2 = U.loc[lambda x: (x > 10) & (x < 25)]
R2
#output
2    19
4    13
dtype: int32
#Filtering values smaller than 10 or larger than 25
#and result saved to a new Series
R3=U.loc[lambda x: (x < 10) | (x > 25)]
R3
#output
0     32
1    301
3      7
dtype: int32
#Filtering values if they match any elements in a specified list
#result saved to a new Series
R4 = U[U.isin([32,301,13,100])]
R4
#output
0     32
1    301
4     13
dtype: int32

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

wilsonzhang746

Recent Posts

what are Transformer, LLM , and GPT

In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…

1 day ago

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

4 days ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

2 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

11 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

1 year ago