[pandas] SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

转载自https://blog.csdn.net/blackyuanc/article/details/77892784

问题场景:

      在读取CSV文件后,在新增一个特征列并根据已有特征修改新增列的值,结果在修改的过程中碰到SettingWithCopyWarning警告。

报错的做法

  1 import pandas as pd
  2 import numpy as np
  3 
  4 aa = np.array([1,0,1,0])
  5 bb = pd.DataFrame(aa.T, columns=['one'])
  6 
  7 bb['two'] = 0
  8 
  9 for i in range(bb.shape[0]):
 10         bb['two'][i] = 1
 11 
 12 print(bb)

正确的做法:

  1 # -*- coding: utf-8 -*-
  2 import pandas as pd
  3 import numpy as np
  4 
  5 aa = np.array([1,0,1,0])
  6 bb = pd.DataFrame(aa.T, columns=['one'])
  7 
  8 # 建立
  9 two = np.zeros(bb.shape[0])
 10 
 11 # 修改
 12 for i in range(bb.shape[0]):
 13     two[i] = random.random()
 14 
 15 # 插入
 16 bb.insert(0,'two',two)
 17 
 18 print(bb)

posted @ 2018-04-18 21:45  wanglei5205  阅读(4008)  评论(0编辑  收藏  举报
levels of contents