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

Question:

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.

Asked By: Anthony Nash

||

Answers:

df = df.assign(a=df['a'].sub(1))
Answered By: wwnde
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.