gpt4 book ai didi

python - settingWithCopyWarning pandas 通过索引设置

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:43 30 4
gpt4 key购买 nike

我正在尝试通过索引选择来设置数据框中列的值。

myindex = (df['city']==old_name) & (df['dt'] >= startDate) & (df['dt'] < endDate)
new_name = 'Boston2
df['proxyCity'].ix[myindex ] = new_name

在上面,我想根据 myindex 中的条件在 proxyCity 列中分配值 Boston2

C:\Users\blah\Anaconda3\lib\site-packages\pandas\core\indexing.py:132: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)

在不引入文档中概述的问题的情况下,做我想做的事情的正确方法是什么?

此链接中的答案using pandas to select rows conditional on multiple equivalencies似乎按照我实现它的方式来做。

我不确定执行此操作的正确方法是什么。

最佳答案

为避免双重索引,更改

df['proxyCity'].ix[myindex ] = new_name

df.loc[myindex, 'proxyCity'] = new_name

它更高效(更少的 __getitem__ 函数调用)并且在大多数情况下,将消除 SettingWithCopyWarning

但是请注意,如果 df 是另一个 DataFrame 的子 DataFrame,则可能会发出 SettingWithCopyWarning即使在使用 df.loc[...] = new_name 时也是如此。在这里,Pandas 警告修改 df 不会影响其他 DataFrame。如果这不是您的意图,那么可以安全地忽略 SettingWithCopyWarning。有关使 SettingWithCopyWarning 静音的方法,请参阅 this post .

关于python - settingWithCopyWarning pandas 通过索引设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41270569/

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