转载: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. 论container的前世今生

    why Normally, thin-client multitiered applications are hard to write because they involve many lines ...

  2. 洛谷P2051 中国象棋(dp)

    题目链接:传送门 题目大意: 在N行M列的棋盘中放象棋中的“炮”,问要使得“炮”两两互不伤害,有多少种放法. 1 ≤ n,m ≤ 100,答案对9999973取模. 思路: 按行更新答案.每行炮可以放 ...

  3. 用requestAnimationFrame优化Web动画

    requestAnimationFrame是什么? 在浏览器动画程序中,我们通常使用一个定时器来循环每隔几毫秒移动目标物体一次,来让它动起来.如今有一个好消息,浏览器开发商们决定:“嗨,为什么我们不在 ...

  4. 监控页面后退前进,浏览器文档加载事件之pageshow、pagehide

    https://www.cnblogs.com/milo-wjh/p/6811868.html http://www.runoob.com/jsref/event-onpageshow.html on ...

  5. 滚动加载图片(懒加载)实现原理(这是旧实现,仅做为获取元素宽高api的参考)

    https://www.cnblogs.com/flyromance/p/5042187.html 本文主要通过以下几方面来说明懒加载技术的原理,个人前端小菜,有错误请多多指出 一.什么是图片滚动加载 ...

  6. doubleclick adx note

    1, cid . is billing_id from  Main.html#PRETARGETING otherwise creative id will not upload to  creati ...

  7. zabbix——拓扑图入门

    zabbix的拓扑图是动态的,当你配置好拓扑图后,一旦网络中那个节点出现了问题,很容易在拓扑图中看出问题具体出在哪个位置. 新建一个拓扑图 我们常用到的图标有rack(机柜)还有rackmountab ...

  8. HBase的几个实示例

    1 开发环境 在进行Hbase开发前,需要安装JDK.Hadoop和Hbase,选择一款合适的开发IDE,具体安装方法就不介绍了,我的开发环境: 操作系统:Ubuntu Java版本:jdk1.8 H ...

  9. Connecting Elixir Nodes with libcluster, locally and on Kubernetes

    转自:https://www.poeticoding.com/connecting-elixir-nodes-with-libcluster-locally-and-on-kubernetes/ Tr ...

  10. lapis 项目添加prometheus 监控

      lapis 是基于openresty 扩展的,所以直接将支持prometheus的模块构建进openresty 就可以了 我使用的是nginx-module-vts 模块 环境准备 我已经构建好了 ...