[问题解决]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

猜你喜欢

转载自www.cnblogs.com/everfight/p/SettingWithCopyWarning.html