[问题解决]pandas DataFrame中经常出现SettingWithCopyWarning

时间:2018-11-08 18:21:51   收藏:0   阅读:7489

先从原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
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!