向 Pandas 中的数据框添加空列时的 SettingWithCopyWarning

时间:2021-05-04 06:14:30

标签: python pandas dataframe

我有一个包含两列的数据框。我正在尝试使用此说明添加一个新的空列:

df['new_col'] = ''

列被添加但有警告:

<ipython-input-16-779f11834aea>: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

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

我到底做错了什么?为什么会触发此警告?

提前致谢

1 个答案:

答案 0 :(得分:1)

使用

df=df.assign(new_col = '')