如何基于现有列条件创建DataFrame新列?代码执行异常求助
Hey there! Let's break down why your apply statement is only hitting the ELSE branch—you're checking for NaN values the wrong way.
The Root Problem
In Pandas, missing values (NaN) aren't strings like "NAN" or "NaN"—they're special floating-point values (or pd.NA for nullable dtypes). When you write x['Eval'] == 'NAN', you're comparing a numeric/nullable value to a string, which will always return False. That's why your code never triggers the IF branch!
Correct Solutions
Here are a few ways to fix this, from direct fixes to more efficient alternatives:
1. Fix the Lambda with isna()
Use Pandas' built-in isna() function to properly detect missing values:
import pandas as pd dataFrame01['final'] = dataFrame01.apply(lambda x: x['Name'] if pd.isna(x['Eval']) else x['Eval'], axis=1)
Or you can call the isna() method directly on the column value:
dataFrame01['final'] = dataFrame01.apply(lambda x: x['Name'] if x['Eval'].isna() else x['Eval'], axis=1)
2. Faster Vectorized Alternatives (Recommended!)
Using apply(axis=1) can be slow for large datasets. Instead, use vectorized operations which are much more efficient:
Option A: np.where
import numpy as np dataFrame01['final'] = np.where(dataFrame01['Eval'].isna(), dataFrame01['Name'], dataFrame01['Eval'])
Option B: fillna (Simplest!)
Since you're replacing missing values in Eval with values from Name, fillna is the most concise approach:
dataFrame01['final'] = dataFrame01['Eval'].fillna(dataFrame01['Name'])
Edge Case Check
If your data actually has string values like "NAN" (not true missing values), then you'd use x['Eval'] == 'NAN'—but this is rare. Double-check your Eval column's dtype with dataFrame01['Eval'].dtype to confirm. If it's object dtype, you might have string-based "missing" values instead of proper NaNs.
内容的提问来源于stack exchange,提问作者Mohd Faheem

