python - 使用 copy() 后设置WithCopyWarning

标签 python pandas copy

我的代码如下。

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

我怎样才能避免收到该消息?

最佳答案

我认为你需要复制因为DataFrame.select_dtypes是切片操作,按列类型过滤,查看Question 3 :

df_numeric=df.select_dtypes(include='number').copy()
df_non_numeric=df.select_dtypes(exclude='number').copy()

如果稍后修改 df_non_numeric 中的值,您会发现修改不会传播回原始数据 (df),并且 Pandas 会发出警告。

关于python - 使用 copy() 后设置WithCopyWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55204404/

相关文章:

python - 快速发出多个 twitter API post 请求

python - 如何更改 DataFrame 列的顺序?

pandas - 如何查询嵌套级别的MultiIndex?

sharepoint - 在 SPListItem 中设置作者字段不会持续存在

java - 使用 Java 复制文件时结果为空

PHP 在生成文档时在服务器上创建文档副本

python - 如何使用 cython 将 python 类公开给 C++

python - Matplotlib 图例中的文本对齐

python - 如何从密集的 Pandas 数据帧中制作完整的矩阵

python - 使用应用程序脚本将 MS Word 文件(保存在云端硬盘中)转换为 Google 文档