Tag Archives: Python Pandas error

Python Pandas Error: KeyError: 0 [How to Solve]

Keyerror: error reported by 0

The following are error codes

I call my own library function and use apply to realize vlookup in Excel. The following is the code

data2 = super_function.vlook_up(data1, ['material group', 'material description'], data, ['material group', 'material group description'])

Error message

KeyError: 0

Error reporting reason

This kind of error reporting is due to the index problem. As a result, some numbers were deleted during the original data processing, resulting in the index starting from 6 instead of 0.

Solution:

Just reassign the index

data1.index = list(range(len(data1)))

result

Run successfully.

Python Pandas Typeerror: invalid type comparison

When reading and processing the data in the CSV file with panda in Python, you may encounter such an error:

TypeError: invalid type comparison

Invalid type comparison

At this time, you can print the data in your data frame


1. There may be no data in some items, which will be displayed as Nan when printing. Nan can’t be compared with any data, and it’s not equal to any value, including himself (so you can also use a! =A to judge whether a is Nan.

Therefore, in the following data processing, if a comparison operation is performed, an error will be reported:

TypeError: invalid type comparison

Method, add parameters when reading the CSV

keep_default_na=False

In this way, entries without data will be recognized as null characters instead of Nan


2. Maybe the data types of different columns in your dataframe are different. Some of them are recognized as STR and some as int. although they all look like numbers, they will also report errors when compared later

At this time, you can add a parameter

converters={'from':str,'to':str} # Convert both the from and to columns to str

The explanation of converters is as follows:

converters: dict, default None
Dict of functions for converting values in certain columns. Keys can either
be integers or column labels

The same type can be compared together