Given, two Series bees
and knees
, if the ith value of bees
is NaN, double the ith value inside knees
.
Expected Result
Solution¶
Explanation
-
Identify which elements of
bees
areNaN
withpd.isna()
.This results in a boolean Series.
-
Suppose we use this boolean Series to index
knees
..The elements it selects are not the ones we want.
knees.loc[pd.isna(bees)]
selects the elements ofknees
whose index matches those ofpd.isna(bees)
with True values.In other words,
pd.isna(bees)
has True values at indexes 3 and 7, soknees.loc[pd.isna(bees)]
selects rows ofknees
with index 3 and 7.However, the problem asked us to double the ith value of
knees
if the ith value ofbees
wasNaN
. The fourth and eighth elements ofbees
areNaN
, so we want to select the fourth and eight elements ofknees
. (Note thatknees
's index is not in sequential order.)To prevent Pandas from using the index of
pd.isna(bees)
to select elements ofknees
, we can remove the index by converting the boolean Series to a NumPy array. Then Pandas will select elements by the position of True values. -
Double the value of those elements.
Easy enough, thanks to the
+=
operator :fontawesome-regular-face-smile: