Pandas DataFrame filter() method with examples

Spread the love

The filter() method in pandas helps us select rows and columns from a dataframe according to the specified index labels.

syntax –

DataFrame.filter(items=None, like=None, regex=None, axis=None)

items – A list of labels or indexes of the rows or columns to keep

like – A string that specifies what the indexes or column labels should contain.

regex – A regular expression of what the indexes or column labels should contain.

axis – axis to filter on. Default columns or 1.

Examples –

Let’s read a dataset to work with.

import pandas as pd

url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv'
df = pd.read_csv(url)
df.head()

1 . Select columns using filter() method –

Let’s say that you want to select the Items and Net Sales columns.

df.filter(items=['Items','Net Sales'])

You can also use regular expressions to select columns using the filter() method.

df.filter(regex='e$')

2 . Select rows using filter() method –

To select rows from the dataframe, we need to set the axis parameter to axis=0 or index.

df.filter(items=[0, 2, 5], axis=0)

Related Posts –

  1. Pandas – Select Rows and Columns from a DataFrame.

Rating: 1 out of 5.

Leave a Reply