Pandas >> SettingWithCopyWarning in Pandas

2023-02-05 Pandas

Table of Contents

In this tutorial, we will talk about how to deal with SettingWithCopyWarning in Pandas. How to disable or avoid the warning messages in Pandas.

Pandas

A Sample of SettingWithCopyWarning

Here is an example of code that generates a “SettingWithCopyWarning” in Pandas:

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})

# Make a copy of a slice of the DataFrame
df_slice = df[df['col1'] == 1]

# Try to assign a new value to a new column in the slice
df_slice['col3'] = 7

Pandas

Why and How to Deal with it

The “SettingWithCopyWarning” in Pandas occurs when you try to assign a value to a new column in a DataFrame that is a copy of a slice of the original DataFrame, instead of a reference to the original DataFrame. To avoid this warning and ensure that the assignment is made to the original DataFrame, use the .loc or .iloc accessor to explicitly reference the original DataFrame. For example:

df.loc[:, 'new_column'] = some_value

For the above code, you can use the following code to assign new value to col3.

df.loc[df['col1'] == 1, 'col3'] = 7

Disable Warning Message

You can disable the “SettingWithCopyWarning” in Pandas by adding the following code at the beginning of your script:

import warnings
warnings.filterwarnings("ignore")

However, it is generally not recommended to disable warnings, as they are provided to inform you about possible issues with your code. In this case, the warning is indicating that you are making a potentially dangerous assignment to a copy of a DataFrame instead of the original DataFrame. To avoid the warning and ensure that your code is correct, you should modify your code as described in the above section.

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us