Python Pandas:双条件判断与多列条件新列分类技术问题
Hey there! Let's break down your two Pandas questions with practical examples using the sample data you shared. First, here's a cleaned-up version of your sample DataFrame (fixed the incomplete product_category entry so we can actually run code against it):
import pandas as pd df = pd.DataFrame({ 'customer_id': ['abc','abc','xyz','xyz','xyz','xyz','thr','thr','abc','abc','urt','urt'], 'transaction_id': ['A123','A123','B345','B345','C567','C567','D678','D678','E789','E789','D903','F865'], 'product_id': [255472, 251235, 253764,257344,221577,209809,223551,290678,908354,909238,436758,346577], 'product_category': ['X','X','Y','Y','X','X','Z','Z','X','X','Y','Y'] })
1. Writing Multi-Condition Judgments in Pandas
To filter or check rows based on two or more conditions, use boolean indexing with logical operators (& for AND, | for OR). Always wrap each condition in parentheses—operator precedence can trip you up otherwise!
Example 1: Filter rows where customer is 'abc' AND category is 'X'
# AND condition: both criteria must be true filtered_df = df[(df['customer_id'] == 'abc') & (df['product_category'] == 'X')] print(filtered_df)
Example 2: Filter rows where transaction ID is unique OR product ID > 300000
# OR condition: either criteria can be true # First, create a helper flag for unique transactions df['is_unique_transaction'] = df['transaction_id'].duplicated(keep=False) == False filtered_df = df[(df['is_unique_transaction']) | (df['product_id'] > 300000)] print(filtered_df)
2. Creating a New Column with Conditional Classification
There are a few go-to methods for this, depending on how complex your rules are:
Method 1: np.where for Simple Multi-Condition Logic
Perfect for binary or nested binary rules. Let's create a customer_segment column with these rules:
- If
customer_idis 'abc' ANDproduct_categoryis 'X' → High Value - Else if
customer_idis 'xyz' AND has multiple unique transactions → Repeat Buyer - Else → General
import numpy as np # Pre-check if customer 'xyz' has multiple unique transactions xyz_has_multiple_trans = df.groupby('customer_id')['transaction_id'].nunique()['xyz'] > 1 df['customer_segment'] = np.where( (df['customer_id'] == 'abc') & (df['product_category'] == 'X'), 'High Value', np.where( (df['customer_id'] == 'xyz') & xyz_has_multiple_trans, 'Repeat Buyer', 'General' ) )
Method 2: df.apply() for Complex Custom Logic
If your rules are too nested for np.where, use a custom function with apply() (note: this is slower for large DataFrames, but ideal for intricate logic):
def classify_segment(row): if row['customer_id'] == 'abc' and row['product_category'] == 'X': return 'High Value' elif row['customer_id'] == 'xyz': # Check if this customer has multiple unique transactions customer_trans_count = df[df['customer_id'] == row['customer_id']]['transaction_id'].nunique() if customer_trans_count > 1: return 'Repeat Buyer' # Catch-all for all other cases return 'General' df['customer_segment'] = df.apply(classify_segment, axis=1)
Method 3: pd.cut for Numeric Range Classification
If your classification relies on numeric ranges (like product_id), use pd.cut for clean, vectorized results:
df['product_tier'] = pd.cut( df['product_id'], bins=[0, 250000, 500000, float('inf')], labels=['Low Tier', 'Mid Tier', 'High Tier'] )
Pro tip: Always prioritize vectorized methods like np.where or pd.cut over apply() when possible—they’re drastically faster for large datasets!
内容的提问来源于stack exchange,提问作者jeangelj

