码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-19 13:15:17      阅读:1042      评论:0      收藏:0      [点我收藏+]

标签:sign   other   rbo   created   nbsp   col   write   question   work   

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 DataFrame.

标签:sign   other   rbo   created   nbsp   col   write   question   work   

原文地址:https://www.cnblogs.com/sherrydatascience/p/10291262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!