2016-10-14 63 views
4
df_masked.loc[:, col] = df_masked.groupby([df_masked.index.month, df_masked.index.day])[col].\ 
      transform(lambda y: y.fillna(y.median())) 

即使在使用.loc后,我也得到了foll。错误,我该如何解决它?即使在熊猫中使用.loc后也得到SettingWithCopyWarning警告

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 
+0

我无法重现此问题。你的Pandas版本是什么?您可能还想创建[mcve]。 – Evert

回答

7

你可以得到这个UserWarning如果df_masked一些其他的数据帧的子数据帧。 特别是,如果数据已被复制从原始数据框到df_masked然后,熊猫发出UserWarning警告您修改df_masked将不会影响原始DataFrame。

如果您不打算修改原始DataFrame,那么您可以自由地忽略UserWarning。

There are ways关闭每个语句的UserWarning。特别是,您可以使用df_masked.is_copy = False

如果你遇到这个UserWarning很多,那么不要一个接一个地沉默UserWarnings,我认为最好在开发代码时留下它们。注意UserWarning意味着什么,如果修改这个孩子不影响父母问题不会影响你,那么就忽略它。当你的代码是为生产做好准备,或者如果你是足够的经验来不需要警告,完全用

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:]) 返回副本。

+0

谢谢@unutbu,你是对的,df_masked是副本。 – user308827

+0

这解决了我的问题 – buzhidao