Skip to main content
 首页 » 编程设计

python之pandas之根据另一列更改列中的值

2025年05月04日15pengyingh

假设我有一个数据框all_data,如下所示:

Id  Zone        Neighb 
1   NaN         IDOTRR 
2   RL          Veenker 
3   NaN         IDOTRR 
4   RM          Crawfor 
5   NaN         Mitchel 

我想在“Zone”列中输入缺失值,这样在“Neighb”是“IDOTRR”的地方我将“Zone”设置为“RM”,而在“Neighb”是“Mitchel”的地方我设置“RL” '.

all_data.loc[all_data.MSZoning.isnull()  
             & all_data.Neighborhood == "IDOTRR", "MSZoning"] = "RM" 
all_data.loc[all_data.MSZoning.isnull()  
             & all_data.Neighborhood == "Mitchel", "MSZoning"] = "RL" 

我得到:

TypeError: invalid type comparison

C:\Users\pprun\Anaconda3\lib\site-packages\pandas\core\ops.py:798: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
result = getattr(x, name)(y)

我确信这应该很简单,但我已经弄乱它​​太久了。请帮忙。

请您参考如下方法:

使用 np.select 即

df['Zone'] = np.select([df['Neighb'] == 'IDOTRR',df['Neighb'] == 'Mitchel'],['RM','RL'],df['Zone']) 
   Id Zone   Neighb 
0   1   RM   IDOTRR 
1   2   RL  Veenker 
2   3   RM   IDOTRR 
3   4   RM  Crawfor 
4   5   RL  Mitchel 

In your case of condtions you can use

# Boolean mask of condition 1  
m1 = (all_data.MSZoning.isnull()) & (all_data.Neighborhood == "IDOTRR") 
# Boolean mask of condition 2 
m2 = (all_data.MSZoning.isnull()) & (all_data.Neighborhood == "Mitchel") 
 
np.select([m1,m2],['RM','RL'],all_data["MSZoning"])