w3resource

Pandas Series: filter() function

Subset rows or columns of Pandas dataframe

The filter() function is used to subset rows or columns of dataframe according to labels in the specified index.

Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index.

Syntax:

Series.filter(self, items=None, like=None, regex=None, axis=None)
Pandas Series filter image

Parameters:

Name Description Type/Default Value Required / Optional
items Keep labels from axis which are in items. list-like Required
like Keep labels from axis for which “like in label == True”. string Required
regex Keep labels from axis for which re.search(regex, label) == True. string (regular expression) Required
axis The axis to filter on. By default this is the info axis, ‘index’ for Series, ‘columns’ for DataFrame. int or string axis name Required

Returns: same type as input object

Notes: The items, like, and regex parameters are enforced to be mutually exclusive.
axis defaults to the info axis that is used when indexing with [].

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.array(([2, 3, 4], [5, 6, 7])),
                  index=['bat', 'cat'],
                  columns=['one', 'two', 'three'])
# select columns by name
df.filter(items=['one', 'three'])

Output:

     one	three
bat	2	4
cat	5	7

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.array(([2, 3, 4], [5, 6, 7])),
                  index=['bat', 'cat'],
                  columns=['one', 'two', 'three'])
# select columns by regular expression
df.filter(regex='e$', axis=1)

Output:

     one	 three
bat	 2	    4
cat	 5	    7

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.array(([2, 3, 4], [5, 6, 7])),
                  index=['bat', 'cat'],
                  columns=['one', 'two', 'three'])
# select rows containing 'ca'
df.filter(like='ca', axis=0)

Output:

       one	two	three
cat	   5	6	 7

Previous: Suffix labels with string suffix in Pandas series
Next: Detect missing values in the given Pandas series



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/pandas/series/series-filter.php