shawn kumar
shawn kumar

Reputation: 59

i can't access row 0 in a pandas dataframe - get a KeyError

I've got a pandas dataframe that i've created from a larger df, and i've reset the index. Then I try to take just the value from one column out of the DF but get a keyerror. I've printed out the DF in my if loop and there is definitely an index of 0 there, but I still get the key error:

rows_of_relevance_name = from_csv_df[from_csv_df['Field'].isin(['Patient Name'])].reset_index(drop='True')
if not rows_of_relevance_name.empty:
        print(rows_of_relevance_name)
        print(rows_of_relevance_name[0]['Value'])

KeyError Traceback (most recent call last) in () 19 if not rows_of_relevance_name.empty: 20 print(rows_of_relevance_name) ---> 21 print(rows_of_relevance_name[0]['Value'])*

Upvotes: 0

Views: 3587

Answers (2)

JQTs
JQTs

Reputation: 310

So after an hour of research. this is what solved it for me.

My team kept A1 blank so pandas did not assign it an index.

The code that fixed it for me:

df = pd.read_excel(SAdf, header=1)

That made row 2 my column headers and all done. I can manipulate the data as needed.

#PayItForward

Upvotes: 0

Count Zero
Count Zero

Reputation: 146

If you are trying to access the first row of your dataframe, you should use .iloc[]. You can follow that with more square brackets to pick out the column.

Indexing a dataframe using df[0] is looking for a column named 0.

Your copy and paste job is a little unclear, so I could be interpreting this incorrectly.

Upvotes: 1

Related Questions