简体   繁体   English

创建新列时 Python Pandas SettingWithCopyWarning

[英]Python Pandas SettingWithCopyWarning while creating new column

I have a dataframe df as:我有一个数据框 df 为:

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?执行上述操作的正确方法是什么?

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, ie:但是,如果你想避免警告以保持好习惯,你可以按照消息说的做,即:

df.loc[:, 'newCol'] = df['Month']*2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM