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)
1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.