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-copyhtml

相關文章
相關標籤/搜索