Item Y1961 Y1962 Y1963 Y1964 Y1965 Y1966 Y1967 Y1968 \
8 Wheat 212139 212221 201443 217656 229353 231643 216676 220347
Y1969 ... Y2004 Y2005 Y2006 Y2007 Y2008 Y2009 Y2010 Y2011 \
8 215759 ... 0 0 0 0 0 0 0 0
In the dataframe above, I try to drop the column named 'Item', with the foll. command:
vals_bel_lux.drop('Item', axis=1, inplace=True)
However, this gives me the foll. warning:
C:\Anaconda64\lib\site-packages\pandas\core\generic.py:2602: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
How can I fix this warning?
One approach that can be used to suppress SettingWithCopyWarning is to perform the chained operations into just a single loc operation. This will ensure that the assignment happens on the original DataFrame instead of a copy. Therefore, if we attempt doing so the warning should no longer be raised.
Generally, to avoid a SettingWithCopyWarning in Pandas, you should do the following: Avoid chained assignments that combine two or more indexing operations like df["z"][mask] = 0 and df. loc[mask]["z"] = 0 . Apply single assignments with just one indexing operation like df.
A SettingWithCopyWarning warns the user of a potential bug and should never be ignored even if the program runs as expected. The warning arises when a line of code both gets an item and sets an item. Pandas does not assure whether the get item returns a view or a copy of the dataframe.
Most probably you received the vals_bel_lux
through slicing, in which case the issue is occuring because you are trying to do inplace
drop (by passing inplace=True
argument to drop
method).
If all you want is a new dataframe with the column dropped, you can remove that argument and accept the new DataFrame
that is returned. Example -
vals_bel_lux_new = vals_bel_lux.drop('Item', axis=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With