Net-informations.com

SettingWithCopyWarning in Pandas

The first thing you should understand is that SettingWithCopyWarning is a warning, and not an error. You can safely disable this warning with the following assignment.

  1. None : ignoring the warning
  2. "warn" : printing a warning message
  3. "raise" : raising an exception

Chained Assignment

A chained assignment is used to assign values to a series of variables. The SettingWithCopyWarning was created to flag "chained assignment" operations.

Example

Lets' create a DataFrame with values.

Retrieve the items whose price is greater than 500.

Then, try to update Discount upto 50% whose Price is greater than 500.

Then you will get the SettingWithCopyWarning warning:


how to fix settingwithcopywarning

The real problem behind the warning is that it is generally difficult to predict whether a view or a copy is returned. Here the warning was raised because you have chained two indexing operations together.

This is made easier to spot because you used [] (square brackets) twice, but the same would be true if we used other access methods such as .loc[] , .iloc[] and so on. Here, the chained operations are:

As mentioned in the warning "Try using .loc[row_indexer,col_indexer] = value instead", you can solve this issue by using df.loc[].

Then you can see the DataFrame updated without any warning.


how to handle settingwithcopywarning

What really happend?

When you using df.loc[] ...

It becomes...

In the above code, with a single __setitem__ call to DataFrame.

When you using....

It becomes...

Above code raised the SettingWithCopyWarning waring because depending on whether __getitem__ returned a view or a copy, the __setitem__ operation may not work.

DataFrame View Vs Copy

When filtering Pandas DataFrames , it is possible slice/index a frame to return either a view or a copy. A "View" is a view of the original data, so modifying the view may modify the original data. While, a "Copy" is a replication of data from the original, any changes made to the copy will not affect original data, and any changes made to the original data will not affect the copy.

How to suppress the SettingWithCopyWarning warning?

You can change the behaviour of SettingWithCopyWarning warning using pd.options.mode.chained_assignment with three option "raise"/"warn"/None .

  1. raise : raises a SettingWithCopyException.
  2. warn : issues a SettingWithCopyWarning (default).
  3. None : suppresses the warning.

example










net-informations.com (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About