Select rows that contain specific text using Pandas

To select rows that contain specific text, use the contains() method. Let’s say the following is our CSV file path −


At first, let us read the CSV file and create Pandas DataFrame −

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

Now, let us select rows that contain specific text “BMW” −

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


Following is the code −

import pandas as pd

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

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


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 BMW ...
   Car   Place UnitsSold
3  BMW   Delhi 95

Updated on: 30-Sep-2021


Kickstart Your Career

Get certified by completing the course

Get Started