利用python进行数据处理的时候,经常会使用到pandas这一强大的数据处理模块。将数据存储为DataFrame形式,进行一系列的操作。
之前以及最近在处理数据的时候经常出现到的一个问题,将这个问题记录一下
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 return super().fillna(
问题复现:
import numpy as np
import pandas as pd
df = pd.DataFrame({
'variety': ['beef', 'mutton', 'pork'],
'count': [10, 5, np.nan]
})
df[['count']].fillna(0, inplace=True)
实际项目程序中,需要处理多列填充值的情况,复现的话我只是简单的用一列用于测试。运行程序会出现如标题的警告。
出现这个问题,python还会很贴切的告诉你请参阅文档中的注意事项(See the caveats in the documentation),并给出对应的链接https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
我们点进去一看究竟吧。
Returning a view versus a copy
返回视图与副本
When setting values in a pandas object, care must be taken to avoid what is called chained indexing. Here is an example.
在 Pandas 对象中设置值时,必须小心避免所谓的 chained indexing. 这是一个例子。
In [354]: dfmi = pd.DataFrame([list(