首页 > 解决方案 > `SettingWithCopyWarning` 理解

问题描述

我有如下代码。我收到一堆SettingWithCopyWarning消息。但是,如果我在最后一条语句之后检查 3 个数据帧,则只有df_numeric['class']值 99。在其他两个数据帧中,class值保持不变。为什么?我认为由于SettingWithCopyWarning,在所有数据框中的最后一条语句class值会改变

请解释发生了什么

import pandas as pd
import numpy as np
data = [['Alex',10,5,0],['Bob',12,4,1],['Clarke',13,6,0],['brke',15,1,0]]
df = pd.DataFrame(data,columns=['Name','Age','weight','class'],dtype=float) 

df_numeric=df.select_dtypes(include='number')#, exclude=None)[source]
df_non_numeric=df.select_dtypes(exclude='number')

df_non_numeric['class']=df_numeric['class'].copy()

df_numeric['class']=99

标签: pythonpandascopy

解决方案


在这里快速回答。这是中最常见的警告pandas

就像在 pandas 中理解 SettingwithCopyWarning所说的那样,pandas通知您您的操作可能没有按预期工作,您应该检查结果以确保您没有出错。


的原因SettingwithCopyWarning

SettingwithCopyWarning通常在您尝试将新值分配给df2原始数据框的子集时发生df1

但是原始数据框df1根本没有改变!

在此处输入图像描述 【图借自Understanding SettingwithCopyWarning in pandas

如何把它钉下来?

  1. 我建议您通过详细解释和示例代码阅读这篇文章Understanding SettingwithCopyWarning in pandas
  2. 就像@anky_91 说的,你可以浏览评论列表中的帖子

希望你能度过所有的烂摊子!


推荐阅读