Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

python - Set values of pandas df cell based on conditions

My df is as follows:

enter image description here

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

enter image description here

It sets NaN to other cells

enter image description here

What am I missing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...