1、首先SettingWithCopyWarning不是一种错误Error而是一种警告Warning。
2、该警告一般是在引用pandas中的数据框时发出的警告,我们知道引用数据框数据的方式挺多的,但是一不小心就会返回这个警告。
3、SettingWithCopyWarning的含义是:(1)你的操作可能没有按预期运行,你应该检查结果以确保没有出错。(2)如果希望更改原始数据框,发出这个警告就要检查使用的索引有没有把原始的数据框进行修改。
1 import pandas as pd 2 3 df1 = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"]) 4 df1[["A", "B"]]["A"] = 1000 #想将df1中的A列值改为1000 5 #此时会报出SettingWithCopyWarning警告,而且你会发现df1中的值并未发生改变 6 print(df1) 7 #通过loc索引发现实现了修改df1中的值,也没有警告,这主要因为之前使用了链式索引 8 df1.loc[:, "A"] = 1000 9 print(df1)
1 df1 = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"]) 2 df2 = df1.loc[:, "A"] #类型为pandas中的Series序列 3 df2[0] = 1000 4 print(df2) 5 print(df1) #df1结果也被修改 6 7 df2 = df1.loc[:, ["A", "B"]] #类型为pandas中的DataFrame序列 8 df2["A"] = 0 9 print(df2) 10 print(df1) #df1结果并未改变
参考:https://www.jianshu.com/p/72274ccb647a