1

In a program, I have the following pandas-related operations

df_data['id'][i] = test[‘area’][i]

The code will work, but running the program will generate the following message

C:\Users\AppData\Local\Temp/ipykernel_22744/4097485461.py:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df_data['area'][i] = test['area'][i]

I am not very clear about this message after reading the related documentation, and what should be the best practice to modify this line of operation? Besides, are there any ways to suppress this kind of message without letting them to print out.

user297850
  • 7,705
  • 17
  • 54
  • 76
  • [This answer](https://stackoverflow.com/a/20627316/15497888) by [Garrett](https://stackoverflow.com/users/243434/garrett) covers both the `loc` option and the warning suppression option. – Henry Ecker Nov 13 '21 at 23:13
  • But be warned, there are [lots of issues](https://github.com/pandas-dev/pandas/issues/18752) not using the `loc` as suggested. – Henry Ecker Nov 13 '21 at 23:13

1 Answers1

2

The best/recommended approach is to use loc or iloc (index). You method of assignment is trying to assign to a copy of the dataframe. Using loc or iloc helps assign to the actual dataframe.


df_data.loc[i, 'id'] = test[‘area’][i]

df.iloc[i,j]=1

You will see a more detailed discussion at the link provided in the pandas warning message.

Tim
  • 3,178
  • 1
  • 13
  • 26