logo_learn_stats

Find out how to Medication in Pandas: KeyError: “[‘Label’] not found in axis”

Posted on
banner 336x280

One error it’s possible you’ll stumble upon when the usage of pandas is:

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

This mistake typically happens while you try to let go a column from a pandas DataFrames and fail to remember to specify axis=1.

banner 468x60

By means of default, the axis argument is about to 0 which refers to rows. You should specify axis=1 to inform pandas to take a look at the columns.

Refer to instance presentations methods to recovery this mistake in observe.

Find out how to Reproduce the Error

Think we now have please see pandas DataFrame:

import pandas as pd

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

#view DataFrame
print(df)

        staff	assists	issues
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 assume we try to let go the “points” column from the DataFrame:

#try to let go "points" column
df_new = df.let go('issues')

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

By means of default, the let go() serve as makes use of axis=0, which refers back to the rows of the DataFrame.

Since there’s no row identify referred to as “points” we obtain an error.

Find out how to Medication the Error

To inform pandas to take a look at the columns rather, we should specify axis=1 as follows:

#let go "points" column
df_new = df.let go('issues', axis=1)

#view up to date DataFrame
print(df)

	staff	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

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

It is because we worn axis=1, so pandas knew to take a look at the column names for “points” when deciding which values to let go from the DataFrame.

Alternative Assets

Refer to tutorials provide an explanation for methods to recovery alternative usual mistakes in Python:

Find out how to Medication KeyError in Pandas
Find out how to Medication: ValueError: can not convert glide NaN to integer
Find out how to Medication: ValueError: operands may just no longer be broadcast along side shapes

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *