Python新手求助:如何在Pandas中实现多条件if-elif判断逻辑
Hey there! Since you're new to Python and Pandas, let's tackle this multi-condition mapping problem with some clean, efficient approaches that are easier to maintain than nested lambda expressions. Here are three solid solutions tailored to your needs:
1. Use np.select (Most Intuitive for Multi-Branch Logic)
numpy.select is perfect for this scenario—it lets you define a list of conditions and their corresponding outcomes, making your logic super readable. It’s also efficient for large datasets.
import numpy as np import pandas as pd # Your original data setup df = pd.DataFrame( {'v_contract_number': ['VN120001438','VN120001439', 'VN120001440','VN120001438', 'VN120001439','VN120001440'], 'Collateral': ['Real Estate','Real Estate','Gold','Gold','Deposit','Deposit'], 'Purpose': [20,30,20,30,20,30]} ) cols = ['Collateral', 'Purpose'] df['combined'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1) # Define your conditions and matching results conditions = [ df['combined'] == "Real Estate_20", df['combined'] == "Real Estate_30" ] choices = [ "Real Estate Loan", "Home Mortgage Loan" ] # Apply the logic with a default value for all other cases df['v_purpose'] = np.select(conditions, choices, default="Others") print(df.head())
To add more conditions later, just append new entries to both the conditions and choices lists—they’ll stay aligned automatically.
2. Use Dictionary Mapping + map (Cleanest for Key-Value Pairs)
If your combined values have a clear one-to-one mapping to v_purpose labels, a dictionary is the most concise approach. It’s easy to update and reads like a lookup table.
# Create a mapping dictionary of your rules purpose_mapping = { "Real Estate_20": "Real Estate Loan", "Real Estate_30": "Home Mortgage Loan" } # Map the values, filling unmatched cases with "Others" df['v_purpose'] = df['combined'].map(purpose_mapping).fillna("Others") # Alternative using .get() if you prefer: # df['v_purpose'] = df['combined'].apply(lambda x: purpose_mapping.get(x, "Others"))
Adding new rules is as simple as adding a new key-value pair to the dictionary—no messy condition lists needed.
3. Custom Function + apply (Closest to Native if-elif-else)
If you prefer writing logic that mirrors traditional if-elif-else statements, wrapping the logic in a custom function makes your code easy to follow, especially for more complex rules down the line.
def determine_purpose(combined_string): if combined_string == "Real Estate_20": return "Real Estate Loan" elif combined_string == "Real Estate_30": return "Home Mortgage Loan" else: return "Others" # Apply the function to your combined column df['v_purpose'] = df['combined'].apply(determine_purpose)
This approach feels familiar if you’re coming from a non-Pandas background, and modifying the logic just means updating the function.
Quick Note on Performance
For large datasets, np.select and dictionary mapping will outperform apply (since apply runs row-by-row under the hood). For small datasets like your example, any of these will work great—pick the one that makes the most sense to you!
内容的提问来源于stack exchange,提问作者hoa tran

