There is a dataframe consisting of some actions that users do on the app. I want to add a new column, and store the previous action of the user, using a grupby
and shift
:
dataframe:
session_id | action
100 | click
100 | buy
101 | open
101 | buy
So I use:
df['prev_action'] = df.groupby('session_id')['action'].shift()
Result:
session_id | action | prev_action
100 | click | NA
100 | buy | click
101 | open | NA
101 | buy | open
It works fine and the result seems fine too, but I get the SettingWithCopyWarning
:
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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
I know a littl about SettingWithCopyWarning
, and I want to know how can I change my code to write a better one and don't get the warning (or should I just ignore the warning in this case?)