Data Science

How to fix UnicodeDecodeError utf-8 codec can't decode byte in Python Pandas?

SA Asked by Sarah Jenkins · 14-06-2023
0 upvotes 15,720 views 0 comments
The question

I am trying to read a CSV file using pd.read_csv() in Python, but I keep hitting the UnicodeDecodeError: 'utf-8' codec can't decode byte at a specific position. I've tried changing the file extension and re-saving it, but the error persists. Is there a specific encoding parameter I should be using for Excel-generated CSVs or files containing special characters to make this work? 

3 answers

0
E
Answered on 16-06-2023

This error occurs because the file you are trying to read was not saved using UTF-8 encoding. Most CSV files created in older versions of Excel use cp1252 or ISO-8859-1 (latin1). In your Python code, you can resolve this by adding the encoding parameter to your read function: df = pd.read_csv('file.csv', encoding='latin1') or encoding='cp1252'. If you are unsure of the encoding, you can use the chardet library to detect it automatically. For high-stakes Data Science projects, it is best practice to standardize all raw data into UTF-8 before processing to avoid these "invalid start byte" errors during production runs. 

0
MA
Answered on 17-06-2023

Have you tried opening the file in a text editor like Notepad++? It usually shows the encoding in the bottom right corner, which could save you a lot of guessing time with the Python parameters.

RO 18-06-2023

Mark, that’s a great manual check! I used Notepad++ and saw it was actually encoded in UTF-16. I changed my Pandas code to encoding='utf-16' and the dataframe loaded perfectly. It seems my data source was using a different Unicode standard than I expected.

0
JO
Answered on 19-06-2023

You can also use the errors='replace' or errors='ignore' arguments in your open function if you don't mind losing a few special characters. 

EL 20-06-2023

While 'ignore' works in a pinch, I usually avoid it because it can strip out important data markers. Using the correct 'latin1' encoding as Elena suggested is much safer for data integrity.

Share your thoughts

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

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session