####问题 在读取csv文件之后,需要对缺失值进行处理,使用age的平均值来进行填充缺失值,出现以下警告提示 ```python C:\CODES\pyenv\tensor\lib\site-packages\pandas\core\generic.py:5434: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self._update_inplace(new_data) ``` 具体代码如下: ```python titan = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt') x = titan[['pclass', 'age', 'sex']] y = titan['survived'] # 缺失值处理,用age的平均值进行填补 x['age'].fillna(x['age'].mean(), inplace=True) print(1, x) ``` 查阅资料后得到下面的解决办法 将缺失值处理的那一行代码改成下面的形式 ```python x = x.loc[:,:].copy() x['age'].fillna(x['age'].mean(), inplace=True) ``` 此时再次运行就会正常啦! ####参考 英文版:[Understanding SettingwithCopyWarning in pandas](https://www.dataquest.io/blog/settingwithcopywarning/ "Understanding SettingwithCopyWarning in pandas") 中文翻译:[Pandas 中 SettingwithCopyWarning 的原理和解决方案](https://www.jianshu.com/p/72274ccb647a "Pandas 中 SettingwithCopyWarning 的原理和解决方案") ####注意 注意学会辨识链式索引,并且要避免使用链式索引。如果要更改原始数据,请使用单一赋值操作。如果你想要一个副本,请强制让 Pandas 制作副本。这样可以节省时间,也可以使代码保持严密的逻辑。 此外,即使 SettingWithCopyWarning 只在进行 set 时才会发生,但在进行 get 操作时,最好也避免使用链式索引。链式操作较慢,而且只要你稍后决定进行赋值操作,就会导致问题。 最后修改:2019 年 01 月 10 日 01 : 33 PM © 著作权归作者所有