pandas 尝试使用 .loc[row_indexer,col_indexer] = value 代替警告,即使在使用正式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32573452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:53:29  来源:igfitidea点击:

Try using .loc[row_indexer,col_indexer] = value instead warning even after using the formal

pythonpandas

提问by Pragnya Srinivasan

This is one of the lines in my code where I get the SettingWithCopyWarning:

这是我的代码中获得 SettingWithCopyWarning 的行之一:

value1['Total Population']=value1['Total Population'].replace(to_replace='*', value=4)

Which I then changed to :

然后我改为:

row_index= value1['Total Population']=='*'
value1.loc[row_index,'Total Population'] = 4

This still gives the same warning. How do I get rid of it?

这仍然给出相同的警告。我该如何摆脱它?

Also, I get the same warning for a convert_objects(convert_numeric=True)function that I've used, is there any way to avoid that.

另外,我收到了与我使用过的convert_objects(convert_numeric=True)函数相同的警告,有什么办法可以避免这种情况。

 value1['Total Population'] = value1['Total Population'].astype(str).convert_objects(convert_numeric=True)

This is the warning megsage that I get:

这是我收到的警告消息:

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

试图在来自 DataFrame 的切片副本上设置值。尝试使用 .loc[row_indexer,col_indexer] = value 代替

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

请参阅文档中的警告:http: //pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

回答by Alexander

Have you tried setting directly?:

您是否尝试过直接设置?:

value1.loc[value1['Total Population'] == '*', 'Total Population'] = 4

回答by Pragnya Srinivasan

Got the solution:

得到了解决方案:

I created a new DataFrame and stored the value of only the columns that I needed to work on, it gives me no errors now!

我创建了一个新的 DataFrame 并仅存储了我需要处理的列的值,现在它没有给我任何错误!

Strange, but worked.

奇怪,但有效。

回答by abstrakkt

I was able to avoid the same warning message with syntax like this:

我能够避免使用以下语法出现相同的警告消息:

value1.loc[:, 'Total Population'].replace('*', 4)

Note that the dataframe doesn't need to be re-assigned to itself, i.e. value1['Total Population']=value1['Total Population']...

请注意,不需要将数据帧重新分配给自身,即value1['Total Population']=value1['Total Population']...