Skip to content Skip to sidebar Skip to footer

Python Pandas: How To Avoid Chained Assignment

I have a pandas dataframe with two columns: x and value. I want to find all the rows where x == 10, and for all these rows set value = 1,000. I tried the code below but I get the w

Solution 1:

You should use loc to ensure you're working on a view, on your example the following will work and not raise a warning:

df.loc[df['x'] == 10, 'value'] = 1000

So the general form is:

df.loc[<mask or index label values>, <optional column>] =<new scalar valueorarraylike>

The docs highlights the errors and there is the intro, granted some of the function docs are sparse, feel free to submit improvements.

Post a Comment for "Python Pandas: How To Avoid Chained Assignment"