Reputation: 11
The following lines of code gives me the SettingWithCopyWarning
. I have tried applying .copy()
as suggested in many other answers on this topic, but I cant seem to get the warning to disappear. The line of code which creates the error is the last line where iloc
is invoked. I can't however understand why this should be a problem.
import numpy as np
import pandas as pd
df=pd.DataFrame(np.arange(100), columns =['col1'])
df['col2']=df.loc[:,'col1'].diff()
df['col2'].iloc[0]=0
Can somebody help me understand what creates this warning and what the right syntax would be to avoid it?
Upvotes: 1
Views: 151
Reputation: 2776
df['col2'].iloc[0]=0
uses chained indexing hence the error
df['col2']
.loc[0]
This is frowned upon (and often behaves in unintuitive ways) in pandas. Instead consider the following "correct" ways of doing the same thing:
df.loc[0,'col2'] = 0
df.at[0,'col2'] = 0
df.iloc[0, df.columns.get_loc('col2')] = 0
Or consider
df.fillna(0, inplace=True)
Upvotes: 1