先從原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
解決方法:
- 使用推薦的 .loc[row_indexer,col_indexer] = value
- 如果不知道,就先copy,再賦值。
s = d[d['col_1'] == 0].copy()
s.loc[:, 'col_2'] = 1