user1769197
user1769197

Reputation: 2214

Python: SettingWithCopyWarning

Having read this answer, I tried to do the following to avoid SettingWithCopyWarning.

So I did below. Yet it still generates the warning below. What have I done wrong ?

df_filtered.loc[:,'MY_DT'] = pd.to_datetime(df_filtered['MY_DT'])
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

My column was originally a string

df_filtered['MY_DT']
Out[3]: 
0       4/24/2020
1       4/24/2020
2       4/24/2020
3       4/24/2020
10      4/24/2020
          ...    
1937    4/30/2020
1938    4/30/2020
1939    4/30/2020
1940    4/30/2020
1941    4/30/2020
Name: MY_DT, Length: 1896, dtype: object

Upvotes: 0

Views: 47

Answers (1)

theletz
theletz

Reputation: 1805

Probably df_filtered is a sub dataframe of other one (df?).

This warning means that you try to change df_filtered which is a slice of df, and it will not change df.

In order to avoid this warning you can try to copy the slice:

df_filtered = df_filtered.copy()

Upvotes: 1

Related Questions