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

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)

 

posted @ 2019-01-19 11:53  Sherrrry  阅读(1352)  评论(0编辑  收藏  举报