赋值警告:A value is trying to be set on a copy of a slice from a DataFrame.

错误代码:
示例一:df['supplierId'] = 'FRESH GO LIMITED'
示例二:df.rename(columns={'one':'one_a'}, inplace=True)``df.drop(['one', 'two', 'three'], axis=1, inplace=True)
错误: :::warning 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
df[‘supplierId’] = ‘FRESH GO LIMITED’ # 供应商
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
df.rename(columns={ ::: 解决方案(示例一)
注:先检查示例二有没有warning,如果有,则可能导致示例一的错误,解决掉示例二的warning就可以了

  • 方法一:使用单一赋值操作(loc):data.loc[:, 'supplierId'] = 'FRESH GO LIMITED'
  • 方法二:创建副本再赋值:

winners = data.loc[data.bid == data.price].copy()
winners.loc[304, 'bidder'] = 'therealname'

  • 方法三:关闭警告(强烈不推荐):pd.set_option('mode.chained_assignment', None)

解决方案(示例二)

  • 方法一:df2 = df.rename(columns={'one':'one_a'})

参考自: Pandas SettingwithCopy 警告解决方案