2

I am trying to slice a dataframe in pandas and save it to another dataframe. Let's say df is an existing dataframe and I want to slice a certain section of it into df1. However, I am getting this warning:

/usr/local/lib/python3.5/dist-packages/ipykernel_launcher.py:25: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

I have checked various posts in SO discussing the similar issue (two of them are following):

  1. Setting with copy warning

  2. How to deal with SettingWithCopyWarning in Pandas?

Going through these links, I was able to find issue in following line

   Years=['2010','2011']
   for key in Years:
        df1['GG'][key]=df[key][df[key].Consumption_Category=='GG']

which I then changed to following

   Years=['2010','2011']
   for key in Years:
        df1['GG'][key]=df[key].loc[df['2010'].iloc[:,0]=='GG']

and get away with the warning.

However, when I included another line to drop a certain column from this dataframe, I again this got warning which I am unable to dort out.

   Years=['2010','2011']
   for key in Years:
        df1['GG'][key]=df[key].loc[df['2010'].iloc[:,0]=='GG']
        df1['GG'][key]=df1['GG'][key].drop(['Consumption_Category'],axis=1,inplace=True)
Pankaj
  • 519
  • 2
  • 5
  • 20
  • I leave it here for people with similar problems, as it helps finding such problems way faster: https://stackoverflow.com/questions/22373927/get-traceback-of-warnings – Manaslu Mar 29 '21 at 14:09

1 Answers1

3

Finally after lot of research and going through pandas documentation, I found the answer to my question. The warning which I was getting is because I have put inplace=True in the drop() function. So, I removed the inplace=True and saved the result into new datafrmae. Now I do not get any warning.

   Years=['2010','2011']
   for key in Years:
        df1['GG'][key]=df[key].loc[df['2010'].iloc[:,0]=='GG']
        df1['GG'][key]=df1['GG'][key].drop(['Consumption_Category'],axis=1)
Pankaj
  • 519
  • 2
  • 5
  • 20