+

Python | Pandas Series.filter ()

Series.filter() Pandas Series.filter() returns subsets of rows or columns of data according to with labels at the specified index. Note that this procedure does not filter the information frame based on its content. The filter is applied to index labels.

Syntax: Series.filter (items = None, like = None, regex = None, axis = None)

Parameter:
items: List of axis to restrict to (must not all be present).
like: Keep axis where “arg in col == True”.
regex: Keep axis with re.search (regex, col) == True.
axis: The axis to filter on. By default this is the info axis, `index` for Series, `columns` for DataFrame.

Returns: same type as input object

Example # 1: Use Series.filter () to filter some values ​​in a given series object using regular expressions.

# import pandas as pd

import pandas as pd

 
# Create a series

sr = pd.Series ([ 80 , 25 , 3 , 25 , 24 , 6 ])

 
# Create Index

index_ = [ `Coca Cola ` , ` Sprite` , `Coke` , ` Fanta` , `Dew` , ` ThumbsUp` ]

  
# set index

sr.index = index_

 
# print series

print (sr)

Output:

We will now use Series.filter () to filter these values ​​from a given series object whose index label name contains a space in the name.

# filter values ​​

result = sr. filter (regex = `. .` )

 
# Print the result

print (result)

Output:

As we can see in the output, Series.filter () successfully returned the desired values ​​from the given series object.

Example # 2: Use Series.filter () to filter some values ​​in a given series object using a list of index labels.

# import pandas as pd

import pandas as pd

 
# Create series < / code>

sr = pd.Series ([ `New York` , ` Chicago` , `Toronto` , ` Lisbon` , `Rio` ])

 
# Create index

index_ = [ `City 1` , `City 2` , ` City 3` , `City 4` , `City 5`

  
# set index

sr.index = index_

 
# Print series

print (sr)

Output:

We will now use Series.filter () to filter the values ​​that match the passed index marks in this series object.

# filter values ​​

result = sr. filter (items = [ ` City 2` , `City 4` ])

  
# Print result

print (result)

Output:

As we can see in the output, Series.filter () successfully returned the desired values ​​from the given series object.

Get Solution for free from DataCamp guru