Pandas SettingWithCopy Warning after trying .loc

First I create a new DataFrame. Then create a new frame2 by filtering some data from the frame. Now I want to assign some value to frame2:

import numpy as np from pandas import DataFrame frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'], columns=['Ohio', 'Texas', 'California']) mask = frame['Texas'] > 1 print frame[mask] frame2 = frame.loc[mask] frame2.loc['c', 'Ohio'] = 'me' print frame2 

but I got this warning:

 C:\Python27\lib\site-packages\pandas\core\indexing.py:461: 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 

Why do I keep getting this warning even though I used the recommended .loc syntax? What should I do to avoid this warning?

+5
source share
1 answer

The change

 frame2 = frame.loc[mask] 

to

 frame2 = frame.loc[mask].copy() 

eliminates this warning.

+4
source

Source: https://habr.com/ru/post/1245230/


All Articles