Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Filter Rows Based on Column Values with query function in Pandas?
To filter rows based on column values, we can use the query() function. In the function, set the condition through which you want to filter records. At first, import the required library −
import pandas as pd
Following is our data with Team Records −
team = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75],
['New Zealand', 4, 65], ['South Africa', 5, 50], ['Bangladesh', 6, 40]]
Create a DataFrame from above and add columns as well −
dataFrame = pd.DataFrame(team, columns=['Country', 'Rank', 'Points']) print(dataFrame)
Country Rank Points
0 India 1 100
1 Australia 2 85
2 England 3 75
3 New Zealand 4 65
4 South Africa 5 50
5 Bangladesh 6 40
Using query() with Single Condition
Use query() to filter records with "Rank" equal to 5 −
import pandas as pd
team = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75],
['New Zealand', 4, 65], ['South Africa', 5, 50], ['Bangladesh', 6, 40]]
dataFrame = pd.DataFrame(team, columns=['Country', 'Rank', 'Points'])
print("Fetch Team with Rank 5:")
print(dataFrame.query("Rank == 5"))
Fetch Team with Rank 5:
Country Rank Points
4 South Africa 5 50
Using query() with Multiple Conditions
Here, we have multiple conditions to filter rows −
import pandas as pd
team = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75],
['New Zealand', 4, 65], ['South Africa', 5, 50], ['Bangladesh', 6, 40]]
dataFrame = pd.DataFrame(team, columns=['Country', 'Rank', 'Points'])
print("Fetch Teams with points above 70 and Rank less than 3:")
print(dataFrame.query("Points > 70 and Rank < 3"))
Fetch Teams with points above 70 and Rank less than 3:
Country Rank Points
0 India 1 100
1 Australia 2 85
Common Query Operations
| Operation | Syntax | Example |
|---|---|---|
| Equality | == |
"Rank == 5" |
| Greater than | > |
"Points > 70" |
| Multiple conditions |
and, or
|
"Points > 70 and Rank < 3" |
| String contains | .str.contains() |
"Country.str.contains('India')" |
Conclusion
The query() function provides a readable way to filter DataFrame rows using string expressions. Use logical operators like and, or to combine multiple conditions for complex filtering.
Advertisements
