Pandas still getting SettingWithCopyWarning even after using .loc
Asked Answered
K

4

23

At first, I tried writing some code that looked like this:

import numpy as np
import pandas as pd
np.random.seed(2016)
train = pd.DataFrame(np.random.choice([np.nan, 1, 2], size=(10, 3)), 
                     columns=['Age', 'SibSp', 'Parch'])

complete = train.dropna()    
complete['AgeGt15'] = complete['Age'] > 15

After getting SettingWithCopyWarning, I tried using.loc:

complete.loc[:, 'AgeGt15'] = complete['Age'] > 15
complete.loc[:, 'WithFamily'] = complete['SibSp'] + complete['Parch'] > 0

However, I still get the same warning. What gives?

Kilmer answered 7/8, 2016 at 0:18 Comment(1)
This is the best article I've read on this topic: dataquest.io/blog/settingwithcopywarning It is also addressed in the Pandas docs here: pandas.pydata.org/pandas-docs/stable/…Latinalatinate
I
26

Note: As of pandas version 0.24, is_copy is deprecated and will be removed in a future version. While the private attribute _is_copy exists, the underscore indicates this attribute is not part of the public API and therefore should not be depended upon. Therefore, going forward, it seems the only proper way to silence SettingWithCopyWarning will be to do so globally:

pd.options.mode.chained_assignment = None

When complete = train.dropna() is executed, dropna might return a copy, so out of an abundance of caution, Pandas sets complete.is_copy to a Truthy value:

In [220]: complete.is_copy
Out[220]: <weakref at 0x7f7f0b295b38; to 'DataFrame' at 0x7f7eee6fe668>

This allows Pandas to warn you later, when complete['AgeGt15'] = complete['Age'] > 15 is executed that you may be modifying a copy which will have no effect on train. For beginners this may be a useful warning. In your case, it appears you have no intention of modifying train indirectly by modifying complete. Therefore the warning is just a meaningless annoyance in your case.

You can silence the warning by setting,

complete.is_copy = False       # deprecated as of version 0.24

This is quicker than making an actual copy, and nips the SettingWithCopyWarning in the bud (at the point where _check_setitem_copy is called):

def _check_setitem_copy(self, stacklevel=4, t='setting', force=False):
    if force or self.is_copy:
        ...

If you are really confident you know what you are doing, you can shut off the SettingWithCopyWarning globally with

pd.options.mode.chained_assignment = None # None|'warn'|'raise'

An alternative way to silence the warning is to make a new copy:

complete = complete.copy()

However, you may not want to do this if the DataFrame is large, since copying can take a significant amount of time and memory, and it is completely pointless (except for the sake of silencing a warning) if you know complete is already a copy.

Ignazio answered 7/8, 2016 at 1:8 Comment(2)
Do you think this is consistent? It raises the same warning with drop_duplicates but not with drop.Claar
@ayhan: There is also no warning if complete = complete.assign(AgeGt15=(complete['Age'] > 15)) is used. The mechanism Pandas uses to infer SettingWithCopyWarning is not fool-proof. It catches the most common cases, but not all.Ignazio
S
3

I resolve it by creating copy of dataframe:

complete = train.copy()
Sheathing answered 2/10, 2018 at 5:35 Comment(1)
Although the marked answer recommends using is_copy, it is not the best way to handle as is_copy will also throw an error message saying it is deprecated -- see panda docs. In light of this, copy() is the best way to ensure no warning messages are thrown.Acerose
V
0

I think your .loc solution would work, if it wasn't for the np.nans in the original data frame. You could either complete = train.dropna().reset_index() or Pandas .assign() will avoid SettingWithCopyWarning and is the recommended way of creating new columns, returning a new data frame object. Your example:

complete = complete.assign(**{'AgeGt15': np.where(complete['Age'] > 15, True, False)})
Viva answered 8/11, 2019 at 12:29 Comment(0)
B
0

Column names as list shall resolve.

complete.loc[:, ['AgeGt15']] = complete['Age'] > 15

complete.loc[:, ['WithFamily']] = complete['SibSp'] + complete['Parch'] > 0

Baptista answered 16/4 at 2:26 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Place

© 2022 - 2024 — McMap. All rights reserved.