python - `SettingWithCopyWarning` 理解
问题描述
我有如下代码。我收到一堆SettingWithCopyWarning
消息。但是,如果我在最后一条语句之后检查 3 个数据帧,则只有df_numeric['class']
值 99。在其他两个数据帧中,class
值保持不变。为什么?我认为由于SettingWithCopyWarning
,在所有数据框中的最后一条语句class
值会改变
请解释发生了什么
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()
df_numeric['class']=99
解决方案
在这里快速回答。这是中最常见的警告。pandas
就像在 pandas 中理解 SettingwithCopyWarning所说的那样,pandas
通知您您的操作可能没有按预期工作,您应该检查结果以确保您没有出错。
的原因SettingwithCopyWarning
SettingwithCopyWarning
通常在您尝试将新值分配给df2
原始数据框的子集时发生df1
但是原始数据框df1
根本没有改变!
【图借自Understanding SettingwithCopyWarning in pandas】
如何把它钉下来?
- 我建议您通过详细解释和示例代码阅读这篇文章Understanding SettingwithCopyWarning in pandas
- 就像@anky_91 说的,你可以浏览评论列表中的帖子
希望你能度过所有的烂摊子!
推荐阅读
- javascript - Highcharts 本地 CSV 问题
- recursion - 与python龟相比,超过了最大递归深度
- python - 为什么最大递归调用会出现此错误?
- spring-boot - 例外:oracle.jdbc.driver.T4CConnection.isValid(I)Z 尝试使用 Spring Boot 访问 Oracle 时
- google-bigquery - Postgres 函数作为 BigQuery 中的过程的正确过程语法?
- java - Java代码用IntStream翻转图像,二维数组?
- javascript - 如何将 HTML 转换为 PDF 并与 expo 共享 pdf 文件 react native share (ios) with printToFileAsync
- python - 使用python返回一个非定向路径图
- perl - 尽管“没有警告 qw(experimental::signatures)”,但生成警告消息的签名
- flutter - 我可以从 Flutter 的对话框中更新父状态吗?