Python Pandas 创建新列时设置WithCopyWarning

Python Pandas SettingWithCopyWarning while creating new column

我有一个数据框 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

我正在尝试以下操作:

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

我收到以下警告:

<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

以上的正确做法是什么?

在这种情况下,按照您的方式分配值是安全的。但是,如果您想避免警告以保持好习惯,您可以按照消息中的说明进行操作,即:

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