简体   繁体   中英

Set values of pandas df cell based on conditions

My df is as follows:

在此处输入图像描述

What I want to do is, Condition: Fruit Name is NOT ( Apple or Mango ) and veggie Name == No Action: Set values in Veggie Color and Enjoy Eating = Unicorn

My code is

df.loc[(~df["Fruit Name"].isin(["Apple","Mango"]))& (df["Veggie Name"]=="Potato"),["Veggie Color","Enjoy Eating"]]="Unicorn"

While it does so as follows

在此处输入图像描述

It sets NaN to other cells

在此处输入图像描述

What am I missing?

You didn't use the exact name of the column Enjoy Eating? , so it created a new column called Enjoy Eating with NaN as default values. Just add the question mark and it will work as expected.

df.loc[(~df["Fruit Name"].isin(["Apple","Mango"]))& (df["Veggie Name"]=="Potato"),["Veggie Color","Enjoy Eating?"]]="Unicorn"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM