【问题标题】:How fix SettingWithCopyWarning with Pandas DataFrame Python如何使用 Pandas DataFrame Python 修复 SettingWithCopyWarning
【发布时间】:2022-10-04 19:59:56
【问题描述】:

我正在编写自己的决策树模型,并且我有一个SettingWithCopyWarning来自 Pandas 我无法修复。 决策树有节点,这些节点被询问以了解决策树某个点的最佳节点是什么。每个节点(它是一个类)创建他的方法来为每个数据提供标签并存储它的方法。 例如,我有处理离散数据的节点,它们基本上将每个可能数据的标签存储在一个组中。

class DiscreteNode(Node):
def __init__(self, name, n_classes,
    rank=None, groups=[]):
    super().__init__(name, n_classes, rank)
    self.groups = groups

它们有一个基本方法(称为 get_split_index),如果在组中找到数据值,则返回索引,从而为该数据提供标签,如下所示:

def get_split_index(self, value):
    for group in self.groups:
        if value in group:
            return self.groups.index(group)

决策树是用 Pandas DataFrame 训练的(节点的名称是 DataFrame 的一列),在每个节点处拆分。因此,为了选择一个节点,我需要估计每个节点的分裂性能。为此,我需要处理整个 DataFrame 的每个节点的标签。 看起来很简单,我试着做这样的事情:

node = DiscreteNode(......)
col_to_process = df[col_variable_of_the_node]
labels = node.get_split_index([val for val in col_to_process])
df["label"] = labels

它就像我想要的那样工作......但它引发了一个SettingWithCopyWarning

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
See the caveats in the documentation: https://pandas.pydata.org/pandas-`docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy`
df["label"] = labels

当然,我试图这样做:

df.loc[:,"label"] = labels

但这并不能解决问题..

我做了一些研究,我了解到问题是我影响了一个来自链接过程的值(使用df["labels"] 设置方法)(获取数据框的列,然后获取每个值)。但我不知道如何以另一种方式做到这一点。

我试过这个,希望它能解决问题:

node = DiscreteNode(......)
col_to_process = df[col_variable_of_the_node]
series = df[col_to_process].values.tolist()
labels = [node.get_split_index(val) for val in series]
df["label"] = labels

但还是有一个SettingWithCopyWarning,我不明白熊猫如何在转换列表中的熊猫列后识别链接,但确实如此。

我怎样才能解决这个问题 ? 谢谢

【问题讨论】:

    标签: python pandas dataframe warnings decision-tree


    【解决方案1】:

    好的...我找到了

    我只是添加了这一行,没有更多警告:

    node = DiscreteNode(......)
    col_to_process = df[col_variable_of_the_node]
    labels = node.get_split_index([val for val in col_to_process])
    df_with_label = df.copy()
    df_with_label["label"] = labels
    

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 2018-06-20
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 2014-10-18
      • 2018-12-25
      相关资源
      最近更新 更多