转载: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的更多相关文章

  1. [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= ...

  2. [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文件后,在新增一个特征列并根据已有特征修改 ...

  3. [错误解决]pandas DataFrame中经常出现SettingWithCopyWarning

    先从原dataframe取出一个子dataframe,然后再对其中的元素赋值,例如 s = d[d['col_1'] == 0] s.loc[:, 'col_2'] = 1 就会出现报错: Setti ...

  4. pandas DataFrame 警告(SettingWithCopyWarning)

    转自:https://www.cnblogs.com/pig-fly/p/7875472.html 刚接触python不久,编程也是三脚猫,所以对常用的这几个工具还没有一个好的使用习惯,毕竟程序语言是 ...

  5. Pandas Series和DataFrame的基本概念

    1,创建Series 1.1,通过iterable创建Series Series接收参数是Iterable,不能是Iterator pd.Series(Iterable) 可以多加一个index参数, ...

  6. 学习笔记之pandas

    Python Data Analysis Library — pandas: Python Data Analysis Library https://pandas.pydata.org/ panda ...

  7. 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 ...

  8. pandas使用drop_duplicates去除DataFrame重复项

    DataFrame中存在重复的行或者几行中某几列的值重复,这时候需要去掉重复行,示例如下: data.drop_duplicates(subset=['A','B'],keep='first',inp ...

  9. 【跟着stackoverflow学Pandas】 - Adding new column to existing DataFrame in Python pandas - Pandas 添加列

    最近做一个系列博客,跟着stackoverflow学Pandas. 以 pandas作为关键词,在stackoverflow中进行搜索,随后安照 votes 数目进行排序: https://stack ...

随机推荐

  1. Templates中的标签if

    1.什么是标签 每个标签标示的是不同的服务器端的功能 2.常用标签 1. if 标签 1.基本if结构 {% if 条件 %} % endif %} 2.if ... else ... 结构 {% i ...

  2. 取消svn关联文件夹

    svn没有自带取消svn关联功能,所以我们需要以下脚本 Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Classe ...

  3. linux http配置

    yum install httpd 安装http服务器 启动http服务器即可访问 如果不行的话,试着执行命令 firewall-cmd –permanent –add-service=http(该命 ...

  4. Yocto学习笔记

    1. 指定SRCREV的例子 #kernel-module-m8887-wlan.bb DESCRIPTION = "Marvell M8887 Wifi kernel module&quo ...

  5. keycloak docker-compose 运行

    内容很简单,主要是搭建一个可运行的keycloak 环境,方便开发测试,同时支持数据库的持久化 docker-compose 文件 version: "3" services: a ...

  6. Compoxure 微服务组合proxy 中间件

    Compoxure 是一个不错的微服务组合中间件,使用此工具我们可以快速的进行micro frontends 应用的开发 使用此工具我们可以替换esi+ ssi 的开发模型(尽管都挺不错). 同时支持 ...

  7. 设置 IntelliJ IDEA 的彩色代码主题

    首先,给出一系列 IntelliJ IDEA 代码的彩色主题,供大家选择: VibrantUnknown(Darcula) FadeComments NicePython Solarized Have ...

  8. python中in,not in,比较运算符,格式化输出,编码

    一,python中的in,和not in python中in的作用是检测或查找,例如: c = ‘你好大号胡覅但是啊飞碟说’ b = ‘你好’ print(b in c ) 结果: True c = ...

  9. (转)mysql创建表时反引号的作用

    试用navicat工具查看现网mysql建表语句时,发现表名和字段名都是反引号引起来的 CREATE TABLE `tab_notice_title_tv` ( `i_id` int(11) NOT ...

  10. Vision GUI programming products

    Matrox Design Assistant Tutorial https://www.youtube.com/watch?v=QnE5heA_yWQ merlic https://www.yout ...