Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to modify integer values in a Pandas DataFrame whilst avoiding SettingWithCopyWarning?

I have a heterogenous Pandas DataFrame – columns are a mix of data types. I only want to subtract the values in one of the integer columns for all rows by a fixed constant. That’s it, and it’s that simple. But I keep running into SettingWithCopyWarning.

Take a DataFrame of two columns. The first is of integer, and the second is of string:

df = pd.DataFrame({"a":[10,20,30] , "b":["x","y","z"]})

I want to subtract one from each cell in column "a", so the returning Dataframe would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a b
9 x
19 y
29 z

I’ve tried so many examples, and 9/10 (for want of a better word), don’t even inform the Reader that their example will result in a SettingWithCopyWarning warning.

>Solution :

df = df.assign(a=df['a'].sub(1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading