By Anthony Lethuillier

2017-01-26 09:13:40 8 Comments

The following line of my code causes a warning :

import pandas as pd

s = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
s.loc[-1] = [5,np.nan,np.nan,6]
grouped = s.groupby(['A'])
for key_m, group_m in grouped:
    group_m.loc[-1] = [10,np.nan,np.nan,10]

C:\Anaconda3\lib\site-packages\ipykernel\ SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

According to the documentation this is the recommended way of doing, so what is happening ?

Thanks for your help.


@piRSquared 2017-01-26 09:31:23

The documentation is slightly confusing.

Your dataframe is a copy of another dataframe. You can verify this by running bool(df.is_copy) You are getting the warning because you are trying to assign to this copy.

The warning/documentation is telling you how you should have constructed df in the first place. Not how you should assign to it now that it is a copy.

df = some_other_df[cols]

will make df a copy of some_other_df. The warning suggests doing this instead

df = some_other_df.loc[:, [cols]]

Now that it is done, if you choose to ignore this warning, you could

df = df.copy()


df.is_copy = None

@Josiah Yoder 2018-06-29 14:23:52

is_copy is deprecated. Is there a new technique to use that is "future-approved"?

@piRSquared 2018-06-29 14:37:22

df = df.copy() should work just fine. I personally avoid editing dataframes in place. Each transformation produces a new copy and I overwrite the old one when desired.

Related Questions

Sponsored Content

15 Answered Questions

[SOLVED] How to deal with SettingWithCopyWarning in Pandas?

1 Answered Questions

[SOLVED] Python Pandas Plot Warning

  • 2019-10-17 09:34:04
  • 46 View
  • 0 Score
  • 1 Answer
  • Tags:   python pandas plot

1 Answered Questions

2 Answered Questions

[SOLVED] Grouping / Categorising ages column in Python Pandas

3 Answered Questions

[SOLVED] Dataframe Warning : SettingWithCopyWarning in python

1 Answered Questions

3 Answered Questions

[SOLVED] pandas replace first few 0s with np.nan

  • 2017-11-01 16:17:50
  • user40780
  • 81 View
  • 1 Score
  • 3 Answer
  • Tags:   python pandas

1 Answered Questions

[SOLVED] Convert a column from pandas dataframe from float to int

  • 2017-09-27 03:13:09
  • niukasu
  • 7764 View
  • 3 Score
  • 1 Answer
  • Tags:   python pandas

2 Answered Questions

[SOLVED] Pandas: SettingWithCopyWarning:

  • 2017-07-18 14:55:37
  • salhin
  • 1725 View
  • 6 Score
  • 2 Answer
  • Tags:   python pandas

Sponsored Content