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
loc and iloc are interchangeable when labels are 0-based integers.
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.
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With