I have a dataframe in python as shown below and I need first sort it based on date time and then calculate the percentage of changes from Current_value and Next_value. But for all of the code I have used, a warning is appeared : SettingWithCopyWarning. Even for xorting the dateTime column. I have programmed all these codes based on different stackoverflow answers, but I have faced with this warning.
df:
| Current_value | Next_value | dateTime |
|---|---|---|
| 10 | 15 | 11/12/2021 8:35:27 AM |
| 20 | 25 | 11/12/2021 8:01:36 PM |
| 30 | 35 | 11/11/2021 11:13:15 AM |
| 40 | 35 | 11/12/2021 6:26:07 AM |
| 50 | 25 | 11/12/2021 8:01:36 PM |
So first I sort the dateTime column with this code:
df.sort_values(by=['dateTime'], inplace=True)
However, the warning is this:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
And for calculating the chage percentage, I use these lines of code:
df['change'] = df['Next_value'].sub(df['Current_value'], axis = 0)
df['percentage'] = df[['profit_change']].div(df.Current_value, axis=0)
df['percentage'] = df['percentage'] * 100
Although these lines of code working correctly, for each line of code above, I faces this warning:
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
What should I do?