EN VI

KeyError when using .loc method using Pandas in Python?

2024-03-14 10:30:04
KeyError when using .loc method using Pandas in Python

I have a simple project that I have created using the information that I collected from an excel sheet file (xlsx file).

this is the information I am working with

enter image description here

when I run df.iloc[1] the output is

but when I run df.loc['Amazon'] I get a KeyError for the keyword I am looking for

enter image description here

I have looked into the documentation in pandas and noticed the same syntax as I used in the code below. I am not sure if there has to be other requirements for me to run this particular code.

Am I required to use a specific type of file for this to function properly or am missing a simple syntax in my code?

Solution:

You should set the "Name" column as the index of the DataFrame first.

df.set_index('Name', inplace=True)
// then you can use the cell value of the "Name" column to index
df.loc['Amazon']

Ref: pandas.DataFrame.set_index pandas.DataFrame.loc

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login