pandas DataFrame 警告(SettingWithCopyWarning)的解决
作者:努力飞翔的猪 时间:2023-08-20 07:45:31
刚接触python不久,编程也是三脚猫,所以对常用的这几个工具还没有一个好的使用习惯,毕竟程序语言是头顺毛驴。所以最近在工作中使用的时候在使用pandas的DataFrame时遇到了以下报警:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
debug了半天,也在网上找了很多,还是没有解决,在报警的那一句调了半天,后来发现主要问题并不是出现在报警的那一句。
给个例子复现一下这个问题:
import pandas as pd
A = pd.DataFrame([[1,2,3],[2,3,4],[3,4,5]], columns = ['a','b','c'])
B = A[['a', 'b']]
B['a'] = B['a'] + 1 # same result by using B.loc[:,'a'] = B.loc[:,'a']+ 1
输出:
A
Out[1]:
a b c
0 1 2 3
1 2 3 4
2 3 4 5B
Out[2]:
a b
0 1 2
1 2 3
2 3 4B
Out[3]:
a b
0 2 2
1 3 3
2 4 4
先说一下我的感觉:这个报警主要是说,你当前对B的操作可能会改变另一个DataFrame A,所以你要小心了。(当然实际的警告并不是这个意思,但是“在DataFrame的一个切片的copy上进行操作”我感觉不出来有什么问题,还请大神们解答一下。)
报警出现在第4行,但主要的问题在于第3行:应该使用.loc方法得到新的DataFrame,而不是直接使用[]引用。
C = A.loc[:,['a','b']]
C['a'] = C['a']+1
这样就不会出现报警了。
个人感觉好像是说用.loc是对原有DataFrame的一种复制性引用,而[]的引用则是指针性的引用,和python本身的赋值特性有关。不过我看了A的值也并没有在B被更改时一同被改掉。总之我现在还只是知其然,不知其所以然,希望有大神帮忙解惑。
来源:https://www.cnblogs.com/pig-fly/p/7875472.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
探讨:如何查看和获取SQL Server实例名
解决python nohup linux 后台运行输出的问题
使用C#连接并读取MongoDB数据库
![](https://img.aspxhome.com/file/2023/1/88391_0s.jpg)
使用python编写android截屏脚本双击运行即可
centos下mysql主从复制设置详解
python游戏实战项目之智能五子棋简易版
![](https://img.aspxhome.com/file/2023/7/134797_0s.gif)
Django 用户认证组件使用详解
css实现图片倒影效果
![](https://img.aspxhome.com/file/UploadPic/200711/5/2007115184648157s.jpg)
Javascript Closures (2)
FCKeditor编辑器实战技巧
![](https://img.aspxhome.com/file/UploadPic/200710/8/2007108211717673s.gif)
python批量替换文件名中的共同字符实例
在matlab中创建类似字典的数据结构方式
![](https://img.aspxhome.com/file/2023/5/107475_0s.jpg)
Python绘制百分比堆叠柱状图并填充图案
![](https://img.aspxhome.com/file/2023/5/67265_0s.jpg)
Vue编写炫酷的时钟插件
![](https://img.aspxhome.com/file/2023/2/139702_0s.gif)
MySQL利用profile分析慢sql详解(group left join效率高于子查询)
Python动态导入模块的方法实例分析
Python用K-means聚类算法进行客户分群的实现
![](https://img.aspxhome.com/file/2023/5/92345_0s.jpg)
Python设计模式之工厂模式简单示例
![](https://img.aspxhome.com/file/2023/1/75341_0s.png)
Python利用matplotlib画出漂亮的分析图表
![](https://img.aspxhome.com/file/2023/4/109414_0s.png)