1. 程式人生 > >[問題解決]pandas DataFrame中經常出現SettingWithCopyWarning

[問題解決]pandas DataFrame中經常出現SettingWithCopyWarning

先從原dataframe取出一個子dataframe,然後再對其中的元素賦值,例如

s = d[d['col_1'] == 0]
s.loc[:, 'col_2'] = 1

就會出現報錯:
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
解決方法:

  1. 使用推薦的 .loc[row_indexer,col_indexer] = value
  2. 如果不知道,就先copy,再賦值。
s = d[d['col_1'] == 0].copy()
s.loc[:, 'col_2'] = 1