The real problem of why you are getting the error is not that there is anything wrong with your code: you can use either iloc
, loc
, or apply
, or *=
, another of them could have worked.
The real problem that you have is due to how you created the df DataFrame. Most likely you created your df as a slice of another DataFrame without using .copy().
The correct way to create your df as a slice of another DataFrame is df = original_df.loc[some slicing].copy()
.
The problem is already stated in the error message you got " 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"
You will get the same message in the most current version of pandas too.
Whenever you receive this kind of error message, you should always check how you created your DataFrame. Chances are you forgot the .copy()