Python:使用字典、函数和lambda为DataFrame新增条件列
Hey there! Let's get your DataFrame sorted out with that new column you need. Your initial approach with a dictionary is a good start, but we can refine it to work directly with pandas without manual looping, which is way more efficient.
First, let's fix the core issue with your current code
Your loop is iterating over the dictionary keys instead of the rows in your DataFrame, and it's just printing results instead of assigning them to the new column. Also, there's a typo (df['state'] should be df['id']) and the condition logic isn't targeting each row's value.
Here are 3 clean ways to achieve your desired result:
1. Dictionary Mapping + map() + fillna() (Most Efficient)
This is the pandas-idiomatic way—use a pre-defined mapping for the known IDs, then fill in the rest with your default string:
import pandas as pd df = pd.DataFrame({ 'id': ['id1', 'id2', 'id3', 'id8', 'id9'] }) # Define the exact strings we want for matching IDs id_to_new = { 'id1': 'id1 is cat 1', 'id2': 'id2 is cat 2', 'id3': 'id3 is cat 3' } # Map the IDs, then fill missing values with the default pattern df['new'] = df['id'].map(id_to_new).fillna(df['id'].apply(lambda x: f"{x} is cat 0"))
2. apply() with Nested Ternary Logic (Straightforward)
If you prefer explicit condition checks for each case, use apply() with a lambda function:
df['new'] = df['id'].apply( lambda x: f"{x} is cat 1" if x == 'id1' else f"{x} is cat 2" if x == 'id2' else f"{x} is cat 3" if x == 'id3' else f"{x} is cat 0" )
3. numpy.select() (Great for Multiple Conditions)
For more readability with multiple conditions, use numpy.select():
import pandas as pd import numpy as np df = pd.DataFrame({ 'id': ['id1', 'id2', 'id3', 'id8', 'id9'] }) # List of conditions to check conditions = [ df['id'] == 'id1', df['id'] == 'id2', df['id'] == 'id3' ] # Corresponding values for each condition choices = [ 'id1 is cat 1', 'id2 is cat 2', 'id3 is cat 3' ] # Apply conditions, use default for everything else df['new'] = np.select(conditions, choices, default=df['id'].apply(lambda x: f"{x} is cat 0"))
Result
All three methods will give you exactly the output you want:
id new 0 id1 id1 is cat 1 1 id2 id2 is cat 2 2 id3 id3 is cat 3 3 id8 id8 is cat 0 4 id9 id9 is cat 0
内容的提问来源于stack exchange,提问作者shsh

