close

[Solved] Pandas KeyError: value not in index

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Pandas KeyError: value not in index in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Pandas KeyError: value not in index Error Occurs?

Today I get the following error Pandas KeyError: value not in index in python.

How To Solve Pandas KeyError: value not in index Error ?

  1. How To Solve Pandas KeyError: value not in index Error ?

    To Solve Pandas KeyError: value not in index Error Use reindex to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.

  2. Pandas KeyError: value not in index

    To Solve Pandas KeyError: value not in index Error Use reindex to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.

Solution 1

Use reindex to get all columns you need. It’ll preserve the ones that are already there and put in empty columns otherwise.

p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])

So, your entire code example should look like this:

df = pd.read_csv(CsvFileName)

p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)

columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)

Solution 2

I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header “Gender ” and I had it listed as:

[['Gender']]

If it’s easy enough for you to access your csv, you can use the excel formula trim() to clip any spaces of the cells.

or remove it like this

df.columns = df.columns.to_series().apply(lambda x: x.strip())

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read