For Loop Using Np.where
I'm trying to create a new column in a dataframe that labels animals that are domesticated with a 1. I'm using a for loop, but for some reason, the loop only picks up the last item
Solution 1:
You are setting all non gerbil to 0
in your last loop iteration. That is, when pet
is gerbil
in your last iteration, ALL entries that are not equal to gerbil
will correspond to 0
. This includes entries that are dog
or cat
. You should check all values in pets
at once. Try this:
df['domesticated'] = df['creature'].apply(lambda x: 1 if x in pets else 0)
If you want to stick with np.where
:
df['domesticated'] = np.where(df['creature'].isin(pets), 1, 0)
Post a Comment for "For Loop Using Np.where"