[Python Debug] SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a Data

Posted Sherrrry

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Python Debug] SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a Data相关的知识,希望对你有一定的参考价值。

I Got a SettingWithCopyWarning when I ran the following code:

tmp=date[date[‘date‘].isnull().values==True]
tmp[‘date‘]=tmp[‘text‘].str.extract(regex2,re.VERBOSE)

The details of the Warning are :

/Users/monica/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:23: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

Then I got the inspiration from

https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas

The SettingWithCopyWarning was created to flag potentially confusing "chained" assignments such as the following, which don‘t always work as expected, particularly when the first selection returns a copy

df[df[‘A‘] > 2][‘B‘] = new_val  # new_val not set in df

The warning offers a suggestion to rewrite as follows:

df.loc[df[‘A‘] > 2, ‘B‘] = new_val

Or you can safely disable this new warning with the following assignment.

pd.options.mode.chained_assignment = None  # default=‘warn‘

Since we copied the dataframe firstly, there are some other options.

You can set the is_copy flag to False, which will effectively turn off the check, for that object:

tmp.is_copy = False

Or explicitly copy then no further warning will happen.

In my case, the problem was solved by add .copy( ) method while defining tmp, i.e.,

tmp=date[date[‘date‘].isnull().values==True].copy()
tmp[‘date‘]=tmp[‘text‘].str.extract(regex2,re.VERBOSE)

 

以上是关于[Python Debug] SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a Data的主要内容,如果未能解决你的问题,请参考以下文章

Python的DEBUG LOG

Python中如何Debug

python flask框架学习——开启debug模式

Python debug

python的Debug调试

python debug ——vscode