Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas SettingWithCopyWarning When Using loc [duplicate]

Have a general question on assignments with indexing/slicing using .loc.

Assume the below DataFrame, df:

df:    
    A   B   C
0   a   b   
1   a   b   
2   b   a   
3   c   c   
4   c   a   

code to reproduce:

df = pd.DataFrame({'A':list('aabcc'), 'B':list('bbaca'), 'C':5*[None]})

I create df1 using:

df1=df.loc[df.A=='c']

df1:
    A   B   C
3   c   c   
4   c   a   

I then assign a value to C based upon a value in B using:

df1.loc[df1.B=='a','C']='d'

The assignment works, but I receive a SettingWithCopy warning. Am I doing something wrong or is this the expected functionality? I thought that using .loc would avoid chained assignment. Is there something that I am missing? I am using Pandas 14.1

like image 227
MattB Avatar asked Aug 25 '14 15:08

MattB


People also ask

Can I use ILOC and loc together?

loc and iloc are interchangeable when labels are 0-based integers.

Does loc change the DataFrame?

loc expression will be updated with the value you specify, and they'll be changed directly in the dataframe, so it's a good idea to first test that you're getting the rows/columns you expect without setting the value.


1 Answers

@EdChum answer in comments to OP has solved the issue. i.e. replace

df1=df.loc[df.A=='c']

with

df1=df.loc[df.A=='c'].copy()

this will make it clear your intentions and not raise a warning

like image 182
Yuval Atzmon Avatar answered Sep 19 '22 19:09

Yuval Atzmon