TmSmth
TmSmth

Reputation: 452

Why SettingWithCopyWarning is raised using .loc?

I have checked similar questions on SO with the SettingWithCopyWarning error raised using .loc but I still don't understand why I have the error in the following example.

It appears line 3, I succeed to make it disappear with .copy() but I would like to understand why .loc didn't work specifically here.

Does making a conditional slice creates a view even if it's .loc ?

df = pd.DataFrame( data=[0,1,2,3,4,5], columns=['A'])
df.loc[:,'B'] = df.loc[:,'A'].values
dfa = df.loc[df.loc[:,'A'] < 4,:] # here .copy() removes the error
dfa.loc[:,'C'] = [3,2,1,0]

Edit : pandas version is 1.2.4

Upvotes: 3

Views: 173

Answers (1)

GeorgeLPerkins
GeorgeLPerkins

Reputation: 1146

dfa = df.loc[df.loc[:,'A'] < 4,:]<br>

dfa is a slice of the df dataframe, still referencing the dataframe, a view.
.copy creates a separate copy, not just a view of the first dataframe.

dfa.loc[:,'C'] = [3,2,1,0]

When it's a view not a copy, you are getting the warning : A value is trying to be set on a copy of a slice from a DataFrame.

.loc is locating the conditions you give it, but it's still a view that you're setting values to if you don't make it a copy of the dataframe.

Upvotes: 1

Related Questions