python 使用pandas修改数据到excel,报“SettingwithCopyWarning A value is trying to be set on a copy of a slice from a DataFrame”的解决方法

场景:

通过pandas模块,将测试数据回写到excel,测试数据有写到excel文件,但控制台输出警告信息如下

警告:

SettingwithCopyWarning A value is trying to be set on a copy of a slice from a DataFrame

 

 参考文章:https://www.jianshu.com/p/72274ccb647a

原始代码

大概意思是确保当前更改的只有一个值,可能其他值也会受影响

source_data["actual"][0]=actual_res

修改代码

采用单一赋值的方法,指定了某列某个列名的值,修改过后,正常赋值更新到excel文件,无警告

        source_data = pd.read_excel(filename, sheet_name=sheetname)  # 返回一个DataFrame对象,多维数据结构

        # 单一赋值操作进行更新,除去列名,行数从0开始
        # 使用source_data["actual"][0]=actual_res,会返回SettingwithCopyWarning的警告
        source_data.loc[rowid, "actual"] = actual_res
        source_data.loc[rowid, "result"] = test_res

        # 数据写到excel里面,但是报错
        with pd.ExcelWriter(filename) as writer:
            source_data.to_excel(writer, sheet_name=sheetname, index=False)

posted on 2022-02-18 10:55  刚刚好1  阅读(660)  评论(0编辑  收藏  举报

导航