Setting values ​​on a copy of a slice from a DataFrame

I have a small data frame, say this:

Mass32 Mass44 12 0.576703 0.496159 13 0.576658 0.495832 14 0.576703 0.495398 15 0.576587 0.494786 16 0.576616 0.494473 ... 

I would like to have a moving average of a Mass32 column, so I do this:

 x['Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2) 

It works the same as I have a new column called Mass32s , which contains what I expect from it, but I also get a warning message:

The value is trying to set on a copy of the slice from the DataFrame. Try using .loc [row_indexer, col_indexer] = value instead

See reservations in documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

I am wondering if there is a better way to do this, especially to avoid receiving this warning message.

+5
source share
1 answer

This warning occurs because your dataframe x is a copy of the fragment. It is not easy to understand why, but it has something to do with how you arrived at your current state.

You can create the correct dataframe from x by doing

 x = x.copy() 

This will remove the warning, but it does not match

You should use the DataFrame.loc method as the warning prompts, for example:

 x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2) 
+9
source

All Articles