简体   繁体   中英

raise KeyError(key) from err

I am going to itterate over the taitanic dataset. 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?

It is because you set your dataframe index as PassengerId on this part.

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 . 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
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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