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:

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))

Leave a ReplyCancel reply