Python Pandas - Iterate and fetch the rows that contain the desired text

PythonServer Side ProgrammingProgramming

To iterate and fetch the rows containing the desired text, use the itertuples() and find() method. The itertuples() iterate over DataFrame rows.

At first, let us import the required library with an alias −

import pandas as pd

Our CSV is on the Desktop as shown in the below path −

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

Let us read the CSV file and create Pandas DataFrame −

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

Iterate and fetch the rows containing a specific text. We are fetching Car column with text “Lamborghini” −

for k in dataFrame.itertuples():
   if k[1].find('Lamborghini') != -1:
      print(k)

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)

# iterate and fetch the rows containing a specific text
# we are finding for Car column with text Lamborghini
for k in dataFrame.itertuples():
   if k[1].find('Lamborghini') != -1:
      print(k)

Output

This will produce the following output −

Pandas(Index=5, Car='Lamborghini', Place='Chandigarh', UnitsSold=80)
Pandas(Index=8, Car='Lamborghini', Place='Delhi', UnitsSold=100)
raja
Published on 27-Sep-2021 13:13:57
Advertisements