Skip to content
Advertisement

Pandas: Conditionally replace values based on other columns values

I have a dataframe (df) that looks like this:

JavaScript

Now my goal is for each add_rd in the event column, the associated NaN-value in the environment column should be replaced with a string RD.

JavaScript

What I did so far

I stumbled across df['environment'] = df['environment].fillna('RD') which replaces every NaN (which is not what I am looking for), pd.isnull(df['environment']) which is detecting missing values and np.where(df['environment'], x,y) which seems to be what I want but isn’t working. Furthermore did I try this:

JavaScript

The indexes are missing or some kind of iterator to access the equivalent value in the event column.
And I tried this:

JavaScript

which obviously didn’t worked.

I took a look at several questions but couldn’t build on the suggestions in the answers. Black’s question Simon’s question szli’s question Jan Willems Tulp’s question

So, how do I replace a value in a column based on another columns values?

Advertisement

Answer

Now my goal is for each add_rd in the event column, the associated NaN-value in the environment column should be replaced with a string RD.

As per @Zero’s comment, use pd.DataFrame.loc and Boolean indexing:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement