Let's say I have the following pandas DataFrame:
df = pd.DataFrame({
'team': ['Warriors', 'Warriors', 'Warriors', 'Rockets', 'Rockets'],
'player': ['Stephen Curry', 'Klay Thompson', 'Kevin Durant', 'Chris Paul', 'James Harden']})
When I try to group on the team
column and perform an operation I get a SettingWithCopyWarning
:
for team, team_df in df.groupby(by='team'):
# team_df = team_df.copy() # produces no warning
team_df['rank'] = 10 # produces warning
team_df.loc[:, 'rank'] = 10 # produces warning
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
df_team['rank'] = 10
If I uncomment the line generating a copy of the sub-DataFrame, I don't get the error. Is this generally best practice to avoid this warning or am I doing something wrong?
Note I don't want to edit the original DataFrame df
. Also I know this example can be done a better way but my use case is much more complex and requires grouping an original DataFrame and performing a series of operations based on a different DataFrame and the specs of that unique group.