Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
pandas
bug
communitycreator

What is a SettingWithCopyWarning?

Naima Abrar

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. If it returns the copy, the command modifies it but the copy gets discarded and the original dataframe remains intact.

Pandas either returns a view of an object or creates a copy when there are any filtering operations performed on the dataset. Hence, when a view is modified, the object is modified too. Conversely, copies do not alter the source dataframe. The warning arises to hint that we might be viewing the dataframe instead of working on the copy or vice-versa.

In the example below, the user might want to extract the first two rows but Pandas does not ensure whether the operations are being performed on a copy (on the right) or on the dataframe itself (on the left).

The warning might look something like this since the code is trying to assign all values in column “z” to zero.

Solution

When you use iloc to access rows and columns in the same line of code, the two operations are reduced to a single set operation like shown below.

Another solution to fix the warning would be to explicitly use the .copy() operator whenever part of the dataframe needs to be modified.

RELATED TAGS

python
pandas
bug
communitycreator
RELATED COURSES

View all Courses

Keep Exploring