Pandas: SettingWithCopyWarning [duplicate]

这一生的挚爱 提交于 2019-11-27 12:10:14

As suggested in the error message, you should use loc to do this:

sve2_all.loc[sve2_all['Hgtot ng/l'] > 100] = np.nan

The warning is here to stop you modifying a copy (here sve2_all[sve2_all[' Hgtot ng/l'] > 100] is potentially a copy, and if it is then any modifications would not change the original frame. It could be that it works correctly in some cases but pandas cannot guarantee it will work in all cases... use at your own risk (consider yourself warned! ;) ).

I was getting this warning while trying to reset the contents of an entire DataFrame but couldn't resolve it using loc or iloc:

df.loc[:, :] = new_values # SettingWithCopyWarning
df.iloc[:, :] = new_values # SettingWithCopyWarning

But resolving to the ndarray contained as data solved the problem:

df.values[:, :] = new_values # no warnings and desired behavior

---Problem solved for me---

I had that warring error when i tried to convert float --> int even if i used the ".loc" command. my mistake was that i filtered my dataFrame (with masks) before the operation so the conversion occurred in only a small part of the dataframe item/column, the result was a mixed type column wich create a confuison. i solved the problem by converting the data frame before the masks (data filtration), i hope it will help.

George Zoto

As it is suggested by other users, you can try:

myindex = sve2_all[' Hgtot ng/l'] > 100

sve2_all.loc[myindex, 'yourcolumn'] = np.nan

Keep in mind that if you run into problems creating pivot tables (pivot_table row keyword not supported by pandas 0.16.0 #417) you should use the new syntax of index and columns instead of rows and cols. https://github.com/yhat/ggplot/issues/417

See also:

Pandas SettingWithCopyWarning

http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!