'Pandas numpy how to convert np.where into pandas filter

I have a dataframe df_ac and a logic for this dataframe is:

df_ac['annfact'] = np.where((df_ac['annfact'] == 0) & (df_ac['cert'] == 0), 1, df_ac['annfact'])

How to use pandas filter to convert the above logic, something like this ?

df_ac['annfact'] = df_ac[(df_ac['annfact'] == 0) & (df_ac['cert'] == 0)] =1 ?

And I hope the pandas filter way will faster than np.where

Any friend can help convert the code or any suggestion ?



Solution 1:[1]

You can use a boolean mask to update certain values. This will modify the "annfact" column directly.

mask = (df_ac["annfact"] == 0) & (df_ac["cert"] == 0)
df.loc[mask, "annfact"] = 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jakub