How to Fix in Pandas: KeyError: “[‘Label’] not found in axis”


One error you may encounter when using pandas is:

KeyError: "['Label'] not found in axis"

This error usually occurs when you attempt to drop a column from a pandas DataFrames and forget to specify axis=1.

By default, the axis argument is set to 0 which refers to rows. You must specify axis=1 to tell pandas to look at the columns.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'points': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print(df)

        team	assists	points
0	A	5	11
1	A	7	8
2	A	7	10
3	A	9	6
4	B	12	6
5	B	9	5
6	B	9	9
7	B	4	12

Now suppose we attempt to drop the “points” column from the DataFrame:

#attempt to drop "points" column
df_new = df.drop('points')

KeyError: "['points'] not found in axis"

By default, the drop() function uses axis=0, which refers to the rows of the DataFrame.

Since there is no row name called “points” we receive an error.

How to Fix the Error

To tell pandas to look at the columns instead, we must specify axis=1 as follows:

#drop "points" column
df_new = df.drop('points', axis=1)

#view updated DataFrame
print(df)

	team	assists
0	A	5
1	A	7
2	A	7
3	A	9
4	B	12
5	B	9
6	B	9
7	B	4

Notice that the “points” column has been dropped from the DataFrame and we don’t receive any error.

This is because we used axis=1, so pandas knew to look at the column names for “points” when deciding which values to drop from the DataFrame.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Leave a Reply

Your email address will not be published.