简体   繁体   English

从错误中引发 KeyError(key)

[英]raise KeyError(key) from err

I am going to itterate over the taitanic dataset.我将遍历 taitanic 数据集。 Here is the code:这是代码:

import numpy as np
import pandas as pd

!wget "https://calmcode.io/datasets/titanic.csv"
dt = pd.read_csv("./titanic.csv", index_col=["PassengerId"])

def impute_cabin_values(X):
    for i in range(len(X)):
        print(X["Pclass"][i])

impute_cabin_values(dt)

And then i face with the following error:然后我面临以下错误:

 raise KeyError(key) from err
KeyError: 0

why should index 0 in the print(X["Pclass"][i]) not working?为什么print(X["Pclass"][i])中的索引0不起作用?

It is because you set your dataframe index as PassengerId on this part.这是因为您在此部分将 dataframe 索引设置为PassengerId

dt = pd.read_csv("./titanic.csv", index_col=["PassengerId"])

You are indexing by nonexistent column PassengerId and trying to fetch nonexistent column Pclass instead of pclass .您正在按不存在的列PassengerId进行索引,并尝试获取不存在的列Pclass而不是pclass Assuming this.假设这个。

import numpy as np
import pandas as pd

#!wget "https://calmcode.io/datasets/titanic.csv"
dt = pd.read_csv("./titanic.csv") #, index_col=["PassengerId"])

def impute_cabin_values(X):
    for i in range(len(X)):
        print(X["pclass"][i])

impute_cabin_values(dt)

Results:结果:

1
3
1
3
1
3
3
2
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM