Pandas筛选创建DataFrame后触发SettingWithCopyWarning警告求助
解决Pandas的SettingWithCopyWarning警告问题
问题根源
用test = Final_Recon_read[Final_Recon_read['Remark']== 'Matched']这种切片方式创建DataFrame时,Pandas返回的可能是原DataFrame的视图而非独立副本。后续对test执行原地修改(比如带inplace=True的重命名操作)时,就会触发警告——因为Pandas无法确定你操作的是独立副本还是原数据的视图,担心你无意间修改了原始数据。
可行解决方案
方案1:显式创建独立副本
在筛选数据时直接调用.copy()方法,生成完全独立的DataFrame,后续修改不会关联原数据:
# 筛选时显式生成副本 test = Final_Recon_read[Final_Recon_read['Remark']== 'Matched'].copy() # 优化重命名逻辑:批量生成重名字典,替代循环逐列修改 cols_to_rename = test.columns.difference([ 'GSTIN of supplier', 'Trade/Legal name', 'Invoice number', 'Invoice Date', 'Supply Attract Reverse Charge', 'Place of supply', 'Source','Purchase Voucher no', 'Voucher Type' ]) rename_mapping = {col: f"Last {col}" for col in cols_to_rename} test.rename(columns=rename_mapping, inplace=True)
方案2:避免原地修改,直接生成新对象
放弃inplace=True,通过赋值生成新的DataFrame,彻底规避视图/副本的歧义:
test = Final_Recon_read[Final_Recon_read['Remark']== 'Matched'] cols_to_rename = test.columns.difference([ 'GSTIN of supplier', 'Trade/Legal name', 'Invoice number', 'Invoice Date', 'Supply Attract Reverse Charge', 'Place of supply', 'Source','Purchase Voucher no', 'Voucher Type' ]) rename_mapping = {col: f"Last {col}" for col in cols_to_rename} # 不使用原地修改,直接赋值覆盖 test = test.rename(columns=rename_mapping)
额外优化提示
原代码中循环逐列执行rename的效率极低,批量生成重名字典后一次性修改,既能提升运行速度,也能减少触发警告的潜在风险。
内容的提问来源于stack exchange,提问作者Vishal Sharma
相关产品推荐
相关产品推荐

