- 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
Python Pandas - Query the columns of a DataFrame
To query the columns of a Pandas DataFrame, use the query(). We are querying to filter records. At first, let us create a Pandas DataFrame
dataFrame = pd.DataFrame({"Product": ["SmartTV", "PenDrive", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]})
Using query() to query columns with conditions −
print(dataFrame.query('Opening_Stock >=500 & Closing_Stock < 1000 & Product.str.startswith("P").values'))
Example
Following is the complete code −
import pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "PenDrive", "Speaker", "Earphone"],"Opening_Stock": [300, 700, 1200, 1500],"Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...\n",dataFrame # using query() to query columns print"\nQuerying columns to filter records...\n" print(dataFrame.query('Opening_Stock >=500 & Closing_Stock < 1000 & Product.str.startswith("P").values'))
Output
This will produce the following output −
DataFrame... Closing_Stock Opening_Stock Product 0 200 300 SmartTV 1 500 700 PenDrive 2 1000 1200 Speaker 3 900 1500 Earphone Querying columns to filter records... Closing_Stock Opening_Stock Product 1 500 700 PenDrive
Advertisements