Pandas FutureWarning 链式赋值拷贝警告完整解决

Pandas FutureWarning 链式赋值拷贝警告完整解决

文章目录

一、报错信息

bash 复制代码
C:\Users\Administrator\AppData\Local\Temp\ipykernel_43344\1525745175.py:3: FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment using an inplace method.
The behavior will change in pandas 3.0. This inplace method will never work because the intermediate object on which we are setting values always behaves as a copy.

For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method({col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform the operation inplace on the original object.

二、报错原因

你代码第 3 行出现链式索引 + inplace=True,Pandas 无法确定你操作的是原 DataFrame 还是临时副本,未来 3.0 版本inplace=True会直接失效,所以抛出警告。

三、临时屏蔽警告

如果暂时不想改代码,仅隐藏提示:

python 复制代码
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

注意:只是隐藏提示,底层数据修改不稳定,正式代码必须修复写法。