gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:57:01 28 4
gpt4 key购买 nike

假设我有一个数据框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   Neighb0   1   RM   IDOTRR1   2   RL  Veenker2   3   RM   IDOTRR3   4   RM  Crawfor4   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"])

关于python - pandas - 根据另一列更改列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079393/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com