JINWOO LEE
JINWOO LEE

Reputation: 21

Try using .loc[row_indexer,col_indexer] = value instead

Using python, there are something wrong.

 resource1   #"dataframe"

and,

resource1.loc[(resource1["code"] == ""), "code"] = "nocode"

then, error message is here.

~/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py:537: 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 See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[item] = s

What's wrong with the code?

Upvotes: 2

Views: 4828

Answers (1)

Lukas
Lukas

Reputation: 2312

If you created resource1 from another source i.e. like this:

# original DattaFrame
resource = pd.DataFrame({'code':['aaa', "", 'bb', 'nbn']})
# new DataFrame 
resource1 = resource[resource['code'].str.len()<3]

You get the warning message (but resource1 has been modified). The reason probably is that resource1 is created as a filter from resource and it's not clear if it returns copy or view - a refference to resources instead of new variable (see this link for more details). To avoid this you may use deepcopy function

import copy
resource1 = copy.deepcopy(resource[resource['code'].str.len()<3])

This securely creates brand new DataFrame with filtered data and your code

resource1.loc[(resource1["code"] == ""), "code"] = "nocode"

will work without warning.

Or you may disable chained assignment to reach the same (but warnings are not just anoying, so consider the option carefuly...)

pandas.options.mode.chained_assignment = None

Upvotes: 3

Related Questions