1

I have a dataframe df as:

df.iloc[1:5,1:3]
                   Date  Month
4   2013-01-03 00:00:00      1
6   2013-01-04 00:00:00      1
10  2013-01-07 00:00:00      1
12  2013-01-08 00:00:00      1

I am trying the following:

df['newCol'] = df['Month']*2

I get the following warning:

<input>:1: 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

What is the correct way to do the above?

Zanam
  • 4,607
  • 13
  • 67
  • 143

1 Answers1

2

In this case, it is safe to assign the value the way you did. However, if you want to avoid the warning to keep the good habit, you can do what the message says, i.e.:

df.loc[:, 'newCol'] = df['Month']*2
Arn
  • 1,898
  • 12
  • 26
  • @gyaan.anveyshak I assume you are referring to a different [question](https://stackoverflow.com/questions/65650576/python-getting-settingwithcopywarning-despite-using-df-loc). The issue is not with the method I suggested but with the preliminary steps, in which you are just creating an alias of a dataframe instead of copying it as indicated in the answer to your question. – Arn Jan 10 '21 at 18:48
  • Yes, the problem was with one of the preliminary steps. I figured it out only after I posted the comment. – rahul-ahuja Jan 11 '21 at 01:31