gpt4 book ai didi

python - 为什么 iloc() 的一种使用给出了 SettingWithCopyWarning,而另一种却没有?

转载 作者:行者123 更新时间:2023-11-28 20:31:46 25 4
gpt4 key购买 nike

在一个类的方法中,我使用了这个语句:

self.__datacontainer.iloc[-1]['c'] = value

这样做我得到了“设置复制警告:试图在 DataFrame 的切片副本上设置一个值”

现在我尝试重现此错误并编写以下简单代码:

import pandas, numpy
df = pandas.DataFrame(numpy.random.randn(5,3),columns=list('ABC'))
df.iloc[-1]['C'] = 3

没有错误。为什么我在第一条语句中出现错误,而在第二条语句中却没有?

最佳答案

链式索引

作为documentation以及本网站上的其他几个答案([1][2])建议,链索引被认为是不好的做法,应该避免。

因为似乎没有一种使用基于整数位置的索引(即.iloc)进行赋值而不违反链索引规则(截至pandas v0.23.4),建议尽可能使用基于标签的索引(即.loc)进行分配。

但是,如果您确实需要按行号访问数据,您可以

df.iloc[-1, df.columns.get_loc('c')] = 42

df.iloc[[-1, 1], df.columns.get_indexer(['a', 'c'])] = 42

Pandas 行为怪异

据我了解,您在尝试人为重现错误时收到警告是完全正确的。

到目前为止我发现它取决于数据框的构造方式

df = pd.DataFrame({'a': [4, 5, 6], 'c': [3, 2, 1]})
df.iloc[-1]['c'] = 42 # no warning

df = pd.DataFrame({'a': ['x', 'y', 'z'], 'c': ['t', 'u', 'v']})
df.iloc[-1]['c'] = 'f' # no warning

df = pd.DataFrame({'a': ['x', 'y', 'z'], 'c': [3, 2, 1]})
df.iloc[-1]['c'] = 42 # SettingWithCopyWarning: ...

似乎 pandas(至少 v0.23.4)在链分配时以不同方式处理混合类型和单一类型的数据帧 [3]

def _check_is_chained_assignment_possible(self):
"""
Check if we are a view, have a cacher, and are of mixed type.
If so, then force a setitem_copy check.
Should be called just near setting a value
Will return a boolean if it we are a view and are cached, but a
single-dtype meaning that the cacher should be updated following
setting.
"""
if self._is_view and self._is_cached:
ref = self._get_cacher()
if ref is not None and ref._is_mixed_type:
self._check_setitem_copy(stacklevel=4, t='referant',
force=True)
return True
elif self._is_copy:
self._check_setitem_copy(stacklevel=4, t='referant')
return False

这对我来说真的很奇怪,虽然我不确定它是否不是预期的。

但是,有一个旧的bug具有类似的行为。


更新

根据developers上述行为是预期的。

关于python - 为什么 iloc() 的一种使用给出了 SettingWithCopyWarning,而另一种却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53806570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com