Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas SettingWithCopyWarning after trying .loc

Tags:

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?

like image 693
Osora Avatar asked Mar 17 '16 12:03

Osora


People also ask

What does .LOC return in pandas?

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.

What is SettingWithCopyWarning?

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.

Does LOC modify 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.


1 Answers

Changing

frame2 = frame.loc[mask]

to

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

eliminates this warning.

like image 142
Ami Tavory Avatar answered Dec 31 '22 21:12

Ami Tavory