pandas模块之SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

本文介绍了在使用Python pandas库处理数据时遇到的SettingWithCopyWarning警告。该警告通常出现在尝试对DataFrame的子集进行赋值操作时,由于链式索引可能导致不确定性。为避免此问题,推荐使用.loc方法进行明确的索引操作,以确保直接对原始DataFrame进行修改。了解这一警告有助于提高代码性能和可预测性。
摘要由CSDN通过智能技术生成

利用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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

写代码ing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值