pandas DataFrame 警告(SettingWithCopyWarning)

转自:https://www.cnblogs.com/pig-fly/p/7875472.htmlhtml

刚接触python不久,编程也是三脚猫,因此对经常使用的这几个工具尚未一个好的使用习惯,毕竟程序语言是头顺毛驴。因此最近在工做中使用的时候在使用pandas的DataFrame时遇到了如下报警:python

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了半天,也在网上找了不少,仍是没有解决,在报警的那一句调了半天,后来发现主要问题并非出如今报警的那一句。工具

给个例子复现一下这个问题:post

1 import pandas as pd
2 A = pd.DataFrame([[1,2,3],[2,3,4],[3,4,5]], columns = ['a','b','c'])
3 B = A[['a', 'b']]
4 B['a'] = B['a'] + 1 # same result by using B.loc[:,'a'] = B.loc[:,'a']+ 1

输出:spa

复制代码
A
Out[1]: 
   a  b  c
0  1  2  3
1  2  3  4
2  3  4  5

B
Out[2]: 
   a  b
0  1  2
1  2  3
2  3  4

B
Out[3]: 
   a  b
0  2  2
1  3  3
2  4  4
复制代码

先说一下个人感受:这个报警主要是说,你当前对B的操做可能会改变另外一个DataFrame A,因此你要当心了。(固然实际的警告并非这个意思,可是“在DataFrame的一个切片的copy上进行操做”我感受不出来有什么问题,还请大神们解答一下。)debug

报警出如今第4行,但主要的问题在于第3行:应该使用.loc方法获得新的DataFrame,而不是直接使用[]引用。指针

C = A.loc[:,['a','b']]
C['a'] = C['a']+1

这样就不会出现报警了。code

我的感受好像是说用.loc是对原有DataFrame的一种复制性引用,而[]的引用则是指针性的引用,和python自己的赋值特性有关。不过我看了A的值也并无在B被更改时一同被改掉。总之我如今还只是知其然,不知其因此然,但愿有大神帮忙解惑。htm

相关文章
相关标签/搜索