代码之家  ›  专栏  ›  技术社区  ›  KawaiKx

SettingWithCopyWarning向数据框中添加空列时出错

  •  -1
  • KawaiKx  · 技术社区  · 3 年前

    我有一个有两列的数据帧。我正在尝试使用以下指令添加新的空列:

    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 回复  |  直到 3 年前
        1
  •  1
  •   wwnde    3 年前

    使用

    df=df.assign(new_col = '')