问题解决:SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
转载:y小川
SettingWithCopyWarning 解决方案
问题场景:我在读取csv文件之后,因为要新增一个特征列并根据已有特征修改新增列的值,结果在修改的时候就碰到了SettingWithCopyWarning这个警告,花了很长时间才解决这个问题。
一个简易版的范例
import pandas as pd
import numpy as np aa = np.array([1, 0, 1, 0])
bb = pd.DataFrame(aa.T, columns=['one'])
print(bb)
输出为:

添加一个新列后在输出
bb['two'] = 0
print(bb) output[]:
one two
0 1 0
1 0 0
2 1 0
3 0 0
按条件修改新列再输出就报错了:
for i in range(bb.shape[0]):
if bb['one'][i] == 0:
bb['two'][i] = 1
print(bb) output[]:
C:/PycharmProjects/NaiveBayesProduct/pandas/try_index.py:22: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
bb['two'][i] = 1
one two
0 1 0
1 0 1
2 1 0
3 0 1
这个问题怎么解决呢,我查了stackoverflow上的很多帖子,试了loc/iloc等函数都不管用,最后才发现是顺序错了。正确方案应该是生成好正确的数组再插入dataframe中。下面我把上面的例子用正确地方法再重新生成一遍。
import pandas as pd
import numpy as np aa = np.array([1, 0, 1, 0])
bb = pd.DataFrame(aa.T, columns=['one'])
# 生成一个ndarray,装要插入的值
two = np.zeros(bb.shape[0])
# 按条件修改two
for i in range(bb.shape[0]):
if bb['one'][i] == 0:
two[i] = 1
# 完成后将two插入dataframe中
bb.insert(1,'two', two)
print(bb) output[]:
one two
0 1 0.0
1 0 1.0
2 1 0.0
3 0 1.0
问题解决:SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame的更多相关文章
- [Python Debug] SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
I Got a SettingWithCopyWarning when I ran the following code: tmp=date[date['date'].isnull().values= ...
- [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文件后,在新增一个特征列并根据已有特征修改 ...
- [错误解决]pandas DataFrame中经常出现SettingWithCopyWarning
先从原dataframe取出一个子dataframe,然后再对其中的元素赋值,例如 s = d[d['col_1'] == 0] s.loc[:, 'col_2'] = 1 就会出现报错: Setti ...
- pandas DataFrame 警告(SettingWithCopyWarning)
转自:https://www.cnblogs.com/pig-fly/p/7875472.html 刚接触python不久,编程也是三脚猫,所以对常用的这几个工具还没有一个好的使用习惯,毕竟程序语言是 ...
- Pandas Series和DataFrame的基本概念
1,创建Series 1.1,通过iterable创建Series Series接收参数是Iterable,不能是Iterator pd.Series(Iterable) 可以多加一个index参数, ...
- 学习笔记之pandas
Python Data Analysis Library — pandas: Python Data Analysis Library https://pandas.pydata.org/ panda ...
- Python机器学习实践与Kaggle实战(转)
https://mlnote.wordpress.com/2015/12/16/python%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E5%AE%9E%E8%B7%B5 ...
- pandas使用drop_duplicates去除DataFrame重复项
DataFrame中存在重复的行或者几行中某几列的值重复,这时候需要去掉重复行,示例如下: data.drop_duplicates(subset=['A','B'],keep='first',inp ...
- 【跟着stackoverflow学Pandas】 - Adding new column to existing DataFrame in Python pandas - Pandas 添加列
最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...
随机推荐
- java-抽象类的成员特点
1.成员变量:既可以是变量,也可以是常量.abstract不能修饰成员变量. 2.构造方法:有.用于子类访问父类数据的初始化. 3.成员方法:既可以是抽象的,也可以是非抽象的. - 抽象方法:强制要求 ...
- django 有关session内部函数做法
session在set和调用时其实分别做了三步: def fileupload(request): request.session['k1'] = 'ppp' ''' .生成一个随机字符串 .set_ ...
- mysql插入操作跳过(ignore)、覆盖(replace into)、更新(on duplicate key)
原帖地址:http:.html .insert ignore into 当插入数据时,如出现错误时,如重复数据,将不返回错误,只以警告形式返回.所以使用ignore请确保语句本身没有问题,否则也会被忽 ...
- sailsjs learning note
menu list: custom controller custom 模块使用 custom model custom middleware custom service ? 路由与对应的contr ...
- java 8大数据类型
第一类:逻辑型boolean 第二类:文本型char 1.JAVA中,char占2字节,16位.可在存放汉字 2.char赋值 char a='a'; //任意单个字符,加单引号. char a=' ...
- LeetCode – Number of Islands
Given a -d grid map of 's (water), count the number of islands. An island is surrounded by water and ...
- day08 MapReduce
PS: HDFS对于MapReduce来说,HDFS就是一个就是一个客户端. PS: 离线就是 写sql,sparkh还是写sql 1. MAPREDUCE原理篇(1) Mapreduce是一个分布式 ...
- vue中在页面渲染完之后获取元素(否则动态渲染的元素获取不到)
两种方法: 方法一: 使用$nextTick,在异步获得数据之后再获取元素: 方法二: 在then之后再获取该元素: 问题2:vue中监听改变数组的方法: let idx =; this.listIn ...
- oracle之rman备份
rman必须在oracle的归档模式下才能进行 查看数据库是否为归档状态,在oracle数据库的命令行输入 archive log list; 首先关闭数据库 shutdown immediate; ...
- TCP/IP option data aligement issue cause system broken
1 Problem Description The field reports show that xxx panel will lockup and then reboot while d ...