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

13

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

df["Population"] = round(df["Population"]/1000000,1)

我收到了以下警告:

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)

如何正确完成并避免此类警告?

感谢您的帮助!

1个回答

12

在你获得 df 之前,它是另一个数据框的子集

df = alldf[cond].copy()

或者我们尝试assign

df = df.assign(Population = round(df["Population"]/1000000,1))

2
谢谢。你建议的第二个解决方案已经起作用了。不过,我已经找到了为什么一开始会出现错误的原因。我在一个副本数据框上工作,因为在前一行中我将df分配给了一个副本。我通过这篇文章 https://dev59.com/GFsX5IYBdhLWcg3wf_v3 找到了解决方案。 - idejuan
1
这是一个有价值的资源,可以帮助理解Pandas中的SettingWithCopyWarning问题:https://towardsdatascience.com/explaining-the-settingwithcopywarning-in-pandas-ebc19d799d25 - idejuan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接