- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements