【发布时间】:2021-11-30 10:26:55
【问题描述】:
这是我的代码中获得SettingWithCopyWarning 的行之一:
value1['Total Population']=value1['Total Population'].replace(to_replace='*', value=4)
然后我改为:
row_index= value1['Total Population']=='*'
value1.loc[row_index,'Total Population'] = 4
这仍然给出相同的警告。我该如何摆脱它?
另外,对于我使用过的 convert_objects(convert_numeric=True) 函数,我收到了同样的警告,有什么办法可以避免这种情况。
value1['Total Population'] = value1['Total Population'].astype(str).convert_objects(convert_numeric=True)
这是我收到的警告消息:
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
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
【问题讨论】:
-
因为您同时更新该数据框中的同一组值,您可以尝试使用临时变量来保存结果并应用回列,看看这是否有助于消除警告信息。
-
你用的是什么版本的python和pandas?