Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >fit.resid给出错误'Try using .loc[row_indexer,col_indexer] = value‘?

fit.resid给出错误'Try using .loc[row_indexer,col_indexer] = value‘?
EN

Stack Overflow用户
提问于 2017-06-26 02:58:13
回答 1查看 107关注 0票数 1

以下是数据帧:

代码语言:javascript
运行
AI代码解释
复制
   CNSSSBDVSN     CNSSSBDVS1                CNMCRGNNM  \
0     5941833      Kluskus 1                  Cariboo   
1     5949832        Iskut 6  North Coast / Cote-nord   
2     5941016      Cariboo H                  Cariboo   
3     5955040  Peace River B     Northeast / Nord-est   
4     5941801  Alkali Lake 1                  Cariboo   

                         CNSSSBDVS3  instagram_posts  airports  \
0                    Indian Reserve                0         0   
1                    Indian Reserve                0         0   
2  Regional District Electoral Area                0         0   
3  Regional District Electoral Area                1        17   
4                    Indian Reserve                0         0   

   railway_stations  accommodations  visitor_centers  festivals  \
0                 0               0                0          0   
1                 0               0                0          0   
2                 0               5                0          0   
3                11               0                0          0   
4                 0               0                0          0   

   ports_and_ferry_terminals  attractions  
0                          0            0  
1                          0            0  
2                          0            0  
3                          0            0  
4                          0            0  

下面是代码。在你阅读它之前,我想提到两点: 1.我认为残差或索引出了问题2.如果需要,CNSSSBDVSN可以用作索引

代码语言:javascript
运行
AI代码解释
复制
# -*- coding: utf-8 -*-
import pandas as pd
import statsmodels.formula.api as sm
import matplotlib.pyplot as plt
import scipy.stats as stats

from tabulate import tabulate


if __name__ == "__main__":

    # Read data
    census_subdivision_without_lower_mainland_and_van_island = pd.read_csv('../data/augmented/census_subdivision_without_lower_mainland_and_van_island.csv')

    # Select data
    cities = census_subdivision_without_lower_mainland_and_van_island[census_subdivision_without_lower_mainland_and_van_island['CNSSSBDVS3'] == 'City']
    non_cities = census_subdivision_without_lower_mainland_and_van_island[census_subdivision_without_lower_mainland_and_van_island['CNSSSBDVS3'] != 'City']

    # Fit
    fit_cities = sm.ols(formula="instagram_posts ~ airports + railway_stations + ports_and_ferry_terminals + accommodations + visitor_centers + festivals  + attractions", data=cities).fit()
    fit_non_cities = sm.ols(formula="instagram_posts ~ airports + railway_stations + ports_and_ferry_terminals + accommodations + visitor_centers + festivals  + attractions", data=non_cities).fit()

    print(fit_cities.summary())
    print(fit_non_cities.summary())

    # Residual
    cities['residual'] = fit_cities.resid
    non_cities['residual'] = fit_non_cities.resid

给出错误:

代码语言:javascript
运行
AI代码解释
复制
/Users/Chu/Documents/dssg/done/linear_model_cities.py:27: 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
  cities['residual'] = fit_cities.resid
/Users/Chu/Documents/dssg/done/linear_model_cities.py:28: 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
  non_cities['residual'] = fit_non_cities.resid
EN

回答 1

Stack Overflow用户

发布于 2017-06-26 03:42:29

您的问题是cities是census_subdivision_without_lower_mainland_and_van_island的一部分,如果您想将cities用作自己的数据帧,则可以使用以下命令创建一个副本:

代码语言:javascript
运行
AI代码解释
复制
cities = census_subdivision_without_lower_mainland_and_van_island[census_subdivision_without_lower_mainland_and_van_island['CNSSSBDVS3'] == 'City'].copy()

或者,如果您希望修改原始数据帧,您可以使用loc插入结果,就像前面提到的错误:

代码语言:javascript
运行
AI代码解释
复制
census_subdivision_without_lower_mainland_and_van_island.loc[census_subdivision_without_lower_mainland_and_van_island['CNSSSBDVS3'] == 'City','residuals'] = fit_cities.resid

同样,对于非城市地区也是如此。仅供参考,我会使用较短的dataframe名称,以保持代码的可读性,并保持在推荐的python行限制内

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44752581

复制
相关文章
Pandas和Numpy的视图和拷贝
在Numpy和Pandas中,有两个重要概念,容易混淆,一个是浅拷贝,也称为视图,另外一个是深拷贝,或者就称为拷贝。如果操作不当,Pandas会爆出SettingWithCopyWarning的异常。
老齐
2020/07/01
3.1K0
pandas的apply操作
pandas的apply操作类似于Scala的udf一样方便,假设存在如下dataframe:
机器学习和大数据挖掘
2019/07/01
7540
Pandas切片操作:一个很容易忽视的错误
Pandas是一个强大的分析结构化数据的工具集,主要用于数据挖掘和数据分析,同时也提供数据清洗功能。
统计学家
2020/05/16
2.4K0
pandas的引用与复制
        之前一直以为pandas任何的切片和筛选都是引用,也就是说,会改变最原始的数据。但是前几天发现并不是这样的。
钱塘小甲子
2019/01/28
2.2K0
Python一个万万不能忽略的警告!
Pandas中有一个警告,很有意思,并且出现频率很高,它就是 SettingWithCopyWarning, 既然是个警告,那么我们是不是可以忽略呢。就像标题说的那样,万万不可。并且,这个警告还要引起我们足够重视。知道为什么会出现这个警告,并知道怎么解决,或许帮助你真正从pandas的被动使用者,变为一个Pandas专家。
double
2019/05/29
1.6K0
JavaScript 错误 - throw、try 和 catch
finally 语句在 try 和 catch 语句之后,无论是否有触发异常,该语句都会执行。
陈不成i
2021/07/19
1.1K0
the input device is not a TTY. If you are using mintty, try prefixing the comma
windows上执行Docker命令,如: docker exec -it mysql mysql -uroot -p 就会报错: the input device is not a TTY. I
Happyjava
2020/10/16
2.6K0
the input device is not a TTY. If you are using mintty, try prefixing the comma
关于空难数据集的探索分析导入数据集伤亡分析机型处理时间分析
写在前面: 这是我见过的最严肃的数据集,几乎每一行数据背后都是生命和鲜血的代价。这次探索分析并不妄图说明什么,仅仅是对数据处理能力的锻炼。因此本次的探索分析只会展示数据该有的样子而不会进行太多的评价。有一句话叫“因为珍爱和平,我们回首战争”。这里也是,因为珍爱生命,所以回首空难。现在安全的飞行是10万多无辜的人通过性命换来的,向这些伟大的探索者致敬。 import pandas as pd import numpy as np import matplotlib.pyplot as plt 导入数据
月见樽
2018/04/27
2.1K0
关于空难数据集的探索分析导入数据集伤亡分析机型处理时间分析
python 错误处理:try..exc
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
py3study
2020/01/10
4440
不用try catch,如何机智的捕获错误
我们知道,React中有个特性Error Boundary,帮助我们在组件发生错误时显示“错误状态”的UI。
刘小夕
2020/09/29
2.7K0
不用try catch,如何机智的捕获错误
loc刷分
<?php $useList = array( '账号1'=>'密码1',
用户1191760
2019/02/27
5990
python try语句如何打印错误行(
打印当前.py文件错误行: import sys try: a = [1,2] print a[3] except: s=sys.exc_info() print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno) 打印execfile的打印错误行: try: execfile("tprint.py") except Exception, info: #print info[1] print "Error '%s' happe
py3study
2020/01/10
1.6K0
vue渲染列表时报错Avoid using non-primitive value as key
vue渲染列表时报错Avoid using non-primitive value as key, use string/number value instead
xyzzz
2020/11/25
2.6K0
vue渲染列表时报错Avoid using non-primitive value as key
SpringBoot 中使用HikariPool 报错Possibly consider using a shorter maxLifetime value.
SpringBoot 使用HikariPool遇到: HikariPool-1 – Failed to validate connection com.mysql.jdbc.JDBC4Connection@4933c203 (No operations allowed after connection closed.). Possibly consider using a shorter maxLifetime value. 错误还是比较明显了 就是maxLifetime这个参数配置不合理
全栈程序员站长
2022/09/10
4K0
pandas中的loc和iloc_pandas loc函数
.loc[],中括号里面是先行后列,以逗号分割,行和列分别是行标签和列标签,比如我要得到数字5,那么就就是:
全栈程序员站长
2022/11/09
1.2K0
weblogic错误WebLogic Server is already using this directory.
weblogic.server.ServiceFailureException: Could not obtain an exclusive lock to the embedded LDAP data files directory: ./ainbs_proxy/ldap/ldapfiles because another WebLogic Server is already using this directory. Ensure that the first WebLogic Server is completely shutdown and restart the server. at weblogic.ldap.EmbeddedLDAP.ensureExclusiveAccess(EmbeddedLDAP.java:960) at weblogic.ldap.EmbeddedLDAP.initialize(EmbeddedLDAP.java:222) at weblogic.t3.srvr.T3Srvr.initializeHere(T3Srvr.java:815) at weblogic.t3.srvr.T3Srvr.initialize(T3Srvr.java:669) at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:343) at weblogic.Server.main(Server.java:32) > *************************************************************************** The WebLogic Server did not start up properly. Exception raised: 'weblogic.server.ServiceFailureException: Could not obtain an exclusive lock to the embedded LDAP data files directory: ./ainbs_proxy/ldap/ldapfiles because another WebLogic Server is already using this directory. Ensure that the first WebLogic Server is completely shutdown and restart the server.' Reason: weblogic.server.ServiceFailureException: Could not obtain an exclusive lock to the embedded LDAP data files directory: ./ainbs_proxy/ldap/ldapfiles because another WebLogic Server is already using this directory. Ensure that the first WebLogic Server is completely shutdown and restart the server. *************************************************************************** 进入目录./ainbs_proxy/ldap/ldapfiles 删除索 *lok 他 我所用的机器这个文件时0字节的
西门呀在吹雪
2020/11/09
1.1K0
Python学习 Day 11 错误处理 try 调用堆栈 记录错误 抛出错误
在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因。在操作系统提供的调用中,返回错误码非常常见。比如打开文件的函数open(),成功时返回文件描述符(就是一个整数),出错时返回-1。
统计学家
2019/04/10
1.1K0
独家 | Pandas 2.0 数据科学家的游戏改变者(附链接)
由于其广泛的功能性和多功能性,如果没有 importpandas as pd,几乎不可能做到数据操纵,对吧?
数据派THU
2023/08/08
4650
独家 | Pandas 2.0 数据科学家的游戏改变者(附链接)
Result Maps collection does not contain value for XXX 错误
2020-05-14 11:56:25.887 ERROR 40074 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.builder.IncompleteElementException: **Could not find result map com.sukai.entity.Student] with root cause**
承苏凯
2020/07/24
3.1K0
Result Maps collection does not contain value for XXX 错误
'try(A a = new A())' VS 'try finally'
测试代码地址:https://github.com/kongxiangxin/pine/tree/master/auto-closeable
明年我18
2019/11/23
5610

相似问题

尝试使用.loc[row_indexer,col_indexer] = value

11

熊猫尝试使用.loc[row_indexer,col_indexer] = value

10

警告:尝试使用.loc[row_indexer,col_indexer] = value

21

再次尝试使用.loc[row_indexer,col_indexer] = value

13

Pandas |λ函数的替代方法=> .loc[row_indexer,col_indexer] = value

128
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
社区富文本编辑器全新改版!诚邀体验~
全新交互,全新视觉,新增快捷键、悬浮工具栏、高亮块等功能并同时优化现有功能,全面提升创作效率和体验
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文