
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate and Fetch Rows Containing Desired Text in Python Pandas
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)
Advertisements