2

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?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

@gyaan.anveyshak I assume you are referring to a different question. 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.
Yes, the problem was with one of the preliminary steps. I figured it out only after I posted the comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.