完整报错
/opt/anaconda3/envs/quant_learn/lib/python3.7/site-packages/pandas/core/series.py:1056: SettingWithCopyWarning:
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
cacher_needs_updating = self._check_is_chained_assignment_possible()
解决方法
赋值都是:
左边的变量 = 右边的值
问题出在左边的变量选择上,使用loc[]
或iloc[]
取值,不要直接用下标也不要混用
问题复现&解决
比如下面就会出现警告:
我们想填充这个None的时候:
import pandas as pd
df = pd.DataFrame(data=[
[1, 2, 3, 4],
[2, 2, 3, None],
[3, 2, 3, 4]
], columns=['a', 'b', 'c', 'd'])
df.iloc[1]['d'] = df.iloc[1]['c']
df.loc[df.index[1], 'd'] = df.iloc[1]['c']
修改为下面的代码就OK了:
df.loc[df.index[1], 'd'] = df.iloc[1]['c']