python pandas.loc not finding row name: KeyError

Viewed 2440

This is driving me crazy because it should be so simple and yet it's not working. It's a duplicate question and yet the answers from previous questions don't work.

My csv looks similar to this:

name,val1,val2,val3
ted,1,2,
bob,1,,
joe,,,4

I want to print the contents of row 'joe'. I use the line below and pycharm gives me a KeyError.

print(df.loc['joe'])
2 Answers

The problem with your logic is that you have not let pandas know which column it should search joe for.

print(df.loc[df['name'] == 'joe'])

or

print(df[df['name'] == 'joe'])

Using .loc directly is achievable only on index. If you just used pd.read_csv without mentioning the index, by default pandas will use number as index. You can set name to be the index if it is unique. Then .loc will work:

df.set_index("name")
print(df.loc['joe'])

Another option, and it's how usually working with .loc, is to name specifically what column you refer to:

print(df.loc[df["name"]=="joe"])

Note that the condition df["name"]=="joe" returns a series with true/false for each row. df.loc[...] on that series will return only rows where the value is true, and therefore it will return only rows where name is "joe". Keep that in mind when in future you will try to do more complex conditioning on your dataframe using .loc.

Related