【问题标题】:Keyerror 83 and a value is trying to be set on a copy of a slice from a dataframeKeyerror 83 并且试图在数据帧的切片副本上设置一个值
【发布时间】:2021-02-21 10:34:47
【问题描述】:

导入必要的模块

banking=pd.read_csv("bank.csv",index_col=0)
banking.dropna(axis=0,inplace=True)
banking.insert(17,'deposit_yes',0)
for i in range(0,len(banking['deposit']),1):
    if(banking['deposit'][i]=='yes'):
         banking ['deposit_yes'][i]==1

错误: 试图在数据帧中的切片副本上设置值

密钥错误 83 从 err 中引发 keyerror(key)

数据:https://drive.google.com/file/d/18RGaTG1-ClLAnn3Gm1Rh5PuXLljWdond/view?usp=drivesdk

你能找出错误吗? 谢谢

【问题讨论】:

  • 检查banking['deposit'][i]中的键83,可能是它丢失了,因此出错了。
  • @Krishna Chaurasia 没有缺失值
  • banking.dropna(axis=0,inplace=True),是不是你删除了一些行?没有数据就很难说哪里出了问题,你能把它分享到某个地方并分享链接吗?
  • @Prayson W.Daniel 我正在尝试查找订阅存款的客户的平均年龄。我是数据分析新手。欢迎提出建议
  • @Prayson W.Daniel 谢谢????

标签: python pandas


【解决方案1】:

获取存款客户的平均年龄:

import pandas as pd

URL = "https://drive.google.com/file/d/18RGaTG1-ClLAnn3Gm1Rh5PuXLljWdond/view?usp=drivesdk"

banking = pd.read_csv(f'https://drive.google.com/uc?export=download&id={URL.split("/")[-2]}', index_col=0)

# this will give you the average age of all with deposit of yes

banking[banking['deposit']=='yes']['age'].mean()

# explaining step by step
# filter data to get only deposit is yes
banking[banking['deposit']=='yes']

# select the age column and get mean

banking[banking['deposit']=='yes']['age'].mean()

【讨论】:

    【解决方案2】:

    两件事。

    首先。您在循环中迭代过度索引,但使用标签banking['deposit'][i] 访问数据。 i 应该是标签,而不是索引。

    第二。从不(几乎)迭代行,因为它很慢。使用内置的矢量化功能,在您的情况下获取新列 deposit_yes 您可以应用以下代码

    df = pd.DataFrame({'deposit':['yes', 'no']})
    df['deposit_yes'] = (df['deposit'] == 'yes').astype(int)
    df
    

    结果

    deposit deposit_yes
    0   yes 1
    1   no  0
    

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2021-07-26
      • 2015-10-06
      • 2016-08-24
      • 2018-06-18
      • 2017-08-25
      • 2019-03-30
      • 2018-09-18
      相关资源
      最近更新 更多