0

I am trying to add a new column to my pandas dataframe called cumulative cases and have tried using

df.loc[:,"cumulative cases"] = df["Cases"].cumsum()

this gives me the 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

self.obj[key] = value

I don't understand what I have to do to remove this warning, the output is what I wanted even with this warning

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • provide sample data and desired output – eshirvana Feb 19 '22 at 22:57
  • Why not use `df = df.assign(CumulativeCases=lambda df: df.Cases.cumsum())`? IMHO, this looks cleaner and doesn't use any indexing at all – ForceBru Feb 19 '22 at 23:02
  • 1
    At some point _before_ this provided code you have unsafely subset your DataFrame. Either `new_df = df[cols]` or `new_df = df[mask]` when it should have been `new_df = df[cols].copy()` or `new_df = df[mask].copy()` The warning is letting you know that `df[mask]['col'] = value` may not work because `df[mask]` may produce a copy and recommends that you use `df.loc[mask, 'col'] = value` but that message is not clear here since you're doing something like `new_df = df[mask]` then later doing `new_df[col] = value` which looks to pandas like a (deferred) `df[mask][col] = value` call. – Henry Ecker Feb 19 '22 at 23:49

0 Answers0