First I build a new DataFrame frame. Then create a new frame2 by filtering some data from 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 I keep got this warning although I used the recommended .loc syntax? what i supposed to do to avoid this warning?
Returns a cross-section (row(s) or column(s)) from the Series/DataFrame. Access group of values using labels. Single label. Note this returns the row as a Series.
A SettingWithCopyWarning warns the user of a potential bug and should never be ignored even if the program runs as expected. The warning arises when a line of code both gets an item and sets an item. Pandas does not assure whether the get item returns a view or a copy of the dataframe.
loc expression will be updated with the value you specify, and they'll be changed directly in the dataframe, so it's a good idea to first test that you're getting the rows/columns you expect without setting the value.
Changing
frame2 = frame.loc[mask]
to
frame2 = frame.loc[mask].copy()
eliminates this warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With