Avagut
Avagut

Reputation: 994

Pandas setting a value on a copy of a slice error when updating columns

I have a 3 column pandas dataframe namely: col1, col2, col3
I want to update the dataframe for col1 to be equal col where col 3 = 0
The below code makes the update successfully but its throwing a warning about setting a value on a copy of a slice

df.col1.loc[df.col3==0] = df.col2.loc[df.col3==0]

Any way to fix the code to remove the warning?

Upvotes: 1

Views: 720

Answers (1)

jezrael
jezrael

Reputation: 863226

Use DataFrame.loc instead Series.loc:

#cache to variable
mask = df.col3 == 0
df.loc[mask, 'col1'] = df.loc[mask, 'col2']

There are also another possible ways - mask or numpy.where:

df['col1'] = df['col1'].mask(mask, df['col2'])

df['col1'] = np.where(mask, df['col2'], df['col1'])

Upvotes: 2

Related Questions