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



我有一个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)

什么是正确的方法来避免这种警告?

谢谢你的帮助!

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

df = alldf[cond].copy()

或者我们尝试assign

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

相关内容

最新更新