栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么使用iloc()一种会给出SettingWithCopyWarning,而另一种却没有呢?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么使用iloc()一种会给出SettingWithCopyWarning,而另一种却没有呢?

链索引

正如该站点上的文档和其他几个答案([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

熊猫行为举止奇怪

根据我的理解,当您试图人为地再现错误时,绝对可以期待警告。

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

df = pd.Dataframe({'a': [4, 5, 6], 'c': [3, 2, 1]})df.iloc[-1]['c'] = 42 # no warningdf = pd.Dataframe({'a': ['x', 'y', 'z'], 'c': ['t', 'u', 'v']})df.iloc[-1]['c'] = 'f' # no warningdf = pd.Dataframe({'a': ['x', 'y', 'z'], 'c': [3, 2, 1]})df.iloc[-1]['c'] = 42 # SettingWithCopyWarning: ...

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

尽管我不确定这是否意外,但对我来说似乎真的很奇怪。

但是,还有一个老错误,其行为与此类似。


更新

根据开发人员的预期,上述行为。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661595.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号