[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)

转载于:https://www.cnblogs.com/wanglei5205/p/8877835.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值