Home > Net >  raise KeyError(key) from err
raise KeyError(key) from err

Time:01-24

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 ?

CodePudding user response:

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

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

CodePudding user response:

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
...
  •  Tags:  
  • Related