settingWithCopyWarning通过索引设置pandas [英] settingWithCopyWarning pandas setting via index
问题描述
我试图通过索引选择来设置数据框中列的值。
I am trying to set the value of a column in a dataframe by selecting via an index.
myindex = (df['city']==old_name) & (df['dt'] >= startDate) & (df['dt'] < endDate)
new_name = 'Boston2
df['proxyCity'].ix[myindex ] = new_name
在上面,我想在 proxyCity中分配值
列给出myindex中的条件 Boston2
In the above, I want to assign the value Boston2
in the proxyCity
column given the condition in myindex
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)
在不引入文档中所述问题的情况下,做我想做的事情的正确方法是什么。
What is the correct way to do what I want to do without introducing problems as outlined in the documentation.
此链接中的答案使用pandas选择以多个等价物为条件的行似乎按照我实现它的方式进行。
The answer in this link using pandas to select rows conditional on multiple equivalencies seems to do it the way I implemented it.
我不确定这样做的正确方法是什么。
I'm not sure what is the right way to do this.
推荐答案
为避免双重索引,请更改
To avoid double indexing, change
df['proxyCity'].ix[myindex ] = new_name
到
df.loc[myindex, 'proxyCity'] = new_name
效率更高(更少 __ getitem __
函数调用),在大多数情况下,将消除 SettingWithCopyWarning
。
It's more efficient (fewer __getitem__
function calls) and in most cases, will eliminate the SettingWithCopyWarning
.
但是,请注意,如果 df
是另一个的子数据框架DataFrame,即使使用 df.loc [...] = new_name $,也可以发出
SettingWithCopyWarning
$
C $ C>。在这里,Pandas警告说修改 df
不会影响其他DataFrame。
如果这不是您的意图,那么可以安全地忽略 SettingWithCopyWarning
。有关沉默 SettingWithCopyWarning
的方法,请参阅此帖子。
Note, however, that if df
is a sub-DataFrame of another DataFrame, it is possible for a SettingWithCopyWarning
to be emitted
even when using df.loc[...] = new_name
. Here, Pandas is warning that modifying df
will not affect the other DataFrame.
If that is not your intent then the SettingWithCopyWarning
can be safely ignored. For ways to silence the SettingWithCopyWarning
see this post.
这篇关于settingWithCopyWarning通过索引设置pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!