Select rows that contain specific text using Pandas

PythonServer Side ProgrammingProgramming

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

C:\\Users\\amit_\\Desktop\\SalesRecords.csv

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')]

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 "BMW"
dataFrame = dataFrame[dataFrame['Car'].str.contains('BMW')]
print("\nFetching rows with text BMW ...\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 BMW ...
   Car   Place UnitsSold
3  BMW   Delhi 95
raja
Published on 30-Sep-2021 11:28:40
Advertisements