SettingWithCopyWarning after using copy()(使用 copy() 后的 SettingWithCopyWarning)
问题描述
我的代码如下.
import pandas as pd
import numpy as np
data = [['Alex',10,5,0],['Bob',12,4,1],['Clarke',13,6,0],['brke',15,1,0]]
df = pd.DataFrame(data,columns=['Name','Age','weight','class'],dtype=float)
df_numeric=df.select_dtypes(include='number')#, exclude=None)[source]
df_non_numeric=df.select_dtypes(exclude='number')
df_non_numeric['class']=df_numeric['class'].copy()
它给了我下面的信息
__main__:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
我想让 df_non_numeric
独立于 df_numeric
我根据其他帖子中的建议使用了 df_numeric['class'].copy()
.
i used df_numeric['class'].copy()
based upon suggestions given in other posts.
我怎样才能避免这条消息?
How could i avoid the message?
推荐答案
我认为你需要 copy
因为 DataFrame.select_dtypes
是切片操作,按列类型过滤,勾选问题3:
I think you need copy
because DataFrame.select_dtypes
is slicing operation, filtering by types of column, check Question 3:
df_numeric=df.select_dtypes(include='number').copy()
df_non_numeric=df.select_dtypes(exclude='number').copy()
如果您稍后修改 df_non_numeric
中的值,您会发现修改不会传播回原始数据 (df
),并且 Pandas 会发出警告.
If you modify values in df_non_numeric
later you will find that the modifications do not propagate back to the original data (df
), and that Pandas does warning.
这篇关于使用 copy() 后的 SettingWithCopyWarning的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 copy() 后的 SettingWithCopyWarning


基础教程推荐
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01