[897] Filter a DataFrame using logical operations

发布时间 2023-10-10 08:50:05作者: McDelfino

In Pandas, you can filter a DataFrame using logical operations to select rows that meet specific conditions. You can use logical operators such as & (and), | (or), and ~ (not) to create complex filtering conditions. Here's how to perform logical operations for DataFrame filtering:

Let's say you have a sample DataFrame:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
        'Age': [25, 32, 18, 47, 22],
        'Salary': [50000, 60000, 45000, 75000, 42000]}

df = pd.DataFrame(data)

Now, let's apply various logical operations for filtering:

Filtering Rows Based on a Single Condition:

You can use a single condition to filter rows:

# Filter rows where Age is greater than 30
filtered_df = df[df['Age'] > 30]

Using & (and) for Multiple Conditions:

You can use the & operator to combine multiple conditions:

# Filter rows where Age is greater than 30 and Salary is greater than 55000
filtered_df = df[(df['Age'] > 30) & (df['Salary'] > 55000)]

Using | (or) for Multiple Conditions:

You can use the | operator for an OR condition:

# Filter rows where Age is less than 25 or Salary is greater than 60000
filtered_df = df[(df['Age'] < 25) | (df['Salary'] > 60000)]

Using ~ (not) to Negate a Condition:

You can use the ~ operator to negate a condition:

# Filter rows where Age is not equal to 32
filtered_df = df[~(df['Age'] == 32)]

These are some basic examples of how to perform logical operations for DataFrame filtering. You can create more complex filtering conditions by combining multiple conditions using parentheses, &, |, and ~ as needed to meet your specific criteria.