Home > Software design >  Why can't I make this assignment in a pandas dataframe?
Why can't I make this assignment in a pandas dataframe?

Time:03-04

The code below returns a warning saying "A value is trying to be set on a copy of a slice from a DataFrame". I checked the linked documentation here but didn't quite understand what it meant. Could anyone explain why this is not allowed and how else I could do the assignment?

a = pd.DataFrame({"Tagname": ["xx","yy"], "Value": [1,3], "Min": [3, 3], "Max": [3,3]})
a.loc[1][2]=2

CodePudding user response:

a.loc[1] returns a new series. You then want to index into that series again and set a value. But you never assigned a name to a.loc[1] so the result gets lost.

Use a.iloc[1, 2] = 2 or a.loc[1, 'Min'] = 2.


If you were using lists, your attempt would be equivalent to setting a value in a copy of an inner list. Demo:

>>> l = [[1, 2]]
>>> l[0].copy()[0] = 3
>>> l
[[1, 2]]
  • Related