Getting SettingWithCopy Warning Warning even after using .loc in pandas

df_masked.loc[:, col] = df_masked.groupby([df_masked.index.month, df_masked.index.day])[col].\
            transform(lambda y: y.fillna(y.median()))

Even after using .loc, I get foll. error, how to fix it?

Anaconda\lib\site-packages\pandas\core\indexing.py:476: 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
+6
source share
1 answer

You can get this UserWarning if it df_maskedis a sub-DataFrame of another DataFrame. In particular, if the data was copied from the original DataFrame to df_masked, then Pandas throws UserWarning to warn you that the change df_maskedwill not affect the original DataFrame.

If you are not going to modify the original DataFrame, you can ignore UserWarning.

UserWarning . , df_masked.is_copy = False.

UserWarning , UserWarnings , , , . , UserWarning, -child-does-not-affect-the-parent , . , ,

pd.options.mode.chained_assignment = None

.


, () :

import pandas as pd

df = pd.DataFrame({'swallow':['African','European'], 'cheese':['gouda', 'cheddar']})
df_masked = df.iloc[1:]
df_masked.is_copy = False   # comment-out this line to see the UserWarning
df_masked.loc[:, 'swallow'] = 'forest'

, UserWarning, , , chained-indexing,

df.iloc[1:].loc[:, 'swallow'] = 'forest'

df, (, df.iloc[1:]) .

+10

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


All Articles