0
tag_df = df[['tag', 'date']]    
tag_df['level'] = ['1'] * len(tag_df)

I got a warning message:

 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

I then tried:

tag_df.loc[:, 'level'] = ['1'] * len(tag_df)

But I got the same warning message. What's wrong here?

marlon
  • 6,029
  • 8
  • 42
  • 76
  • tag_df is a copy of a slice. You have at some point _before_ this provided code you have unsafely subset your code. Either `tag_df = df[cols]` or `tag_df = df[mask]` when it should have been `tag_df = df[cols].copy()` or `tag_df = df[mask].copy()` – Henry Ecker Oct 09 '21 at 03:18
  • The warning is letting you know that `df[mask]['col'] = value` will not work because `df[mask]` produces a copy and recommends that you use `df.loc[mask, 'col'] = value` but that message is not helpful here. – Henry Ecker Oct 09 '21 at 03:19
  • @HenryEcker I edited my question. Yes, there is one more line before it. Should I add a copy() function to it after slicing? – marlon Oct 09 '21 at 04:47
  • 2
    Yes. `tag_df = df[['tag', 'date']].copy()` would resolve the issue. – Henry Ecker Oct 09 '21 at 05:02

0 Answers0