DataFrame的空值填充问题,以及由此引发的SettingWithCopy错误?


dfc = pd.DataFrame({'A': ['aaa', np.nan, 'ccc'], 'B': [1, 2, 3], 'C': [np.nan, np.nan, np.nan], 'D': ['mm', np.nan, 10.0]}) A B C D 0 aaa 1 NaN mm 1 NaN 2 NaN NaN 2 ccc 3 NaN 10 dfc.loc[0][['A']]= 100 SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
it turns out that assigning to the product of chained indexing has inherently unpredictable results
dfc.loc[0,'A'] = 100
     A  B   C    D
0  100  1 NaN   mm
1  NaN  2 NaN  NaN
2  ccc  3 NaN   10
cc2 = dfc[['A','B']].fillna(0.0,inplace=True)
# SettingWithCopyWarning:
# A value is trying to be set on a copy of a slice from a DataFrame

cc2 = dfc[['A','B']].fillna(0.0) #works, only on copy
cc1 = dfc.loc[:,['A','B']].fillna(0.0,inplace=True)
#  return: None. using .loc indexed to a list of columns won't support inplace operations

dfc.fillna({'A':0, 'C':0}, inplace=True)  #  works
dfc.fillna({x:0 for x in ['A','C']}, inplace=True)  # also works
dfc.fillna(0.0,inplace=True) # works

 参考链接:http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy

posted on 2017-06-05 20:02  Mrs.Totoro  阅读(3532)  评论(2编辑  收藏  举报

导航