Python Pandas 警告:尝试在 DataFrame 切片的副本上设置值

ide*_*uan 13 python warnings pandas

我有一个 Pandas DataFrame,我想用以下代码更改列的所有值:

df["Population"] = round(df["Population"]/1000000,1)
Run Code Online (Sandbox Code Playgroud)

我收到以下警告:

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
  return super().rename(
<ipython-input-6-59bf041bb022>:2: 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["Population"] = round(df["Population"]/1000000,1)
Run Code Online (Sandbox Code Playgroud)

正确的做法是什么并避免此类警告?

感谢您的帮助!

WeN*_*Ben 12

在你拥有 df 之前,它是其他一些数据帧的子集

df = alldf[cond].copy()
Run Code Online (Sandbox Code Playgroud)

或者我们尝试assign

df = df.assign(Population = round(df["Population"]/1000000,1))
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。您建议的解决方案 2 已有效。尽管如此,我首先发现了错误发生的原因。我正在处理数据帧的副本,因为在前一行中我将 df 分配给副本。我通过这篇文章找到了解决方案/sf/ask/2360936721/ (2认同)