Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas warning while trying to delete column

Tags:

python

pandas

    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?

like image 394
user308827 Avatar asked Sep 24 '15 02:09

user308827


People also ask

How do I turn off settings with copy 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.

How do I stop pandas SettingWithCopyWarning?

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.

What is SettingWithCopyWarning?

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.


1 Answers

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)
like image 129
Anand S Kumar Avatar answered Sep 23 '22 09:09

Anand S Kumar