Filter the rows – Python Pandas

PythonServer Side ProgrammingProgramming

To filter the rows and fetch specific column value, use the Pandas contains() method. At first, let us import the required library with alias −

import pandas as pd

Read the CSV file using the read_csv(). Our CSV file is on the Desktop −

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")

Now, let us filter the rows with specific text −

dataFrame = dataFrame[dataFrame['Car'].str.contains('Lamborghini')]

Example

Following is the code

import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n",dataFrame)

# select rows containing text "Lamborghini"
dataFrame = dataFrame[dataFrame['Car'].str.contains('Lamborghini')]
print("\nFetching rows with text Lamborghini ...\n",dataFrame)

Output

This will produce the following output −

DataFrame...
           Car       Place   UnitsSold
0         Audi   Bangalore          80
1      Porsche      Mumbai         110
2   RollsRoyce        Pune         100
3          BMW       Delhi          95
4     Mercedes   Hyderabad          80
5  Lamborghini  Chandigarh          80
6         Audi      Mumbai         100
7     Mercedes        Pune         120
8  Lamborghini       Delhi         100

Fetching rows with text Lamborghini ...
           Car       Place   UnitsSold
5  Lamborghini  Chandigarh          80
8  Lamborghini       Delhi         100
raja
Published on 27-Sep-2021 12:57:43
Advertisements