In Pandas, applying multiple conditions to filter or manipulate data is a common task. You can do this using boolean indexing or using methods like query()
and loc[]
. Here's how you can apply multiple conditions in Pandas:
Boolean Indexing:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import pandas as pd # Example DataFrame df = pd.DataFrame({ 'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10], 'C': ['x', 'y', 'x', 'y', 'x'] }) # Applying multiple conditions result = df[(df['A'] > 2) & (df['B'] < 10)] |
Using query()
:
1
|
result = df.query('A > 2 & B < 10') |
Using loc[]
with multiple conditions:
1
|
result = df.loc[(df['A'] > 2) & (df['B'] < 10)] |
Each of these methods allows you to specify multiple conditions using logical operators like &
(and), |
(or), and ~
(not). You can combine multiple conditions within parentheses and use these logical operators to create complex conditions.