![](/img/trans.png)
[英]python pandas: A value is trying to be set on a copy of a slice from a DataFrame
[英]Python Pandas Warning: A value is trying to be set on a copy of a slice from a 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.