Q:

How to fix UnicodeDecodeError when reading CSV file in Pandas with Python?

belongs to collection: Python Pandas Programs

0

In pandas, we are allowed to import a CSV file with the help of pandas.read_csv() method. Sometimes, while importing a CSV file we might get the following type of error.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

# Importing pandas package

import pandas as pd

# Importing dataset

data1=pd.read_csv('C:\Users\hp\Desktop\Includehelp\mycsv.csv')

Error:

Fix UnicodeDecodeError | Output 1

Fixing UnicodeDecodeError Error

The easiest way to fix this error is to provide the actual path of the CSV file inside the read_csv() method. The selection of slash ('\') matters a lot. A path of a file may contain a backslash to represent a folder but when it comes to pass the complete path as a parameter inside the method, we need to use the forward slash ('/') to import the CSV file successfully.

Example:

# Importing pandas package

import pandas as pd

# Importing dataset

data=pd.read_csv('C:/Users/hp/Desktop/Includehelp/mycsv.csv')

# Print the dataset

print(data)

Output:

Fix UnicodeDecodeError | Output 2

Sometimes, read_csv() method takes encoding option as a parameter to deal with files in different formats. Try to use encoding= utf-8" to fix the error. Other alternative for encoding="utf-8" is encoding="ISO-8859-1".

Example:

# Importing pandas package

import pandas as pd

# Importing dataset

data=pd.read_csv('C:/Users/hp/Desktop/Includehelp/mycsv1.csv', encoding="utf-8")

# Print the dataset

print(data)

Output:

Fix UnicodeDecodeError | Output 3

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Constructing pandas DataFrame from values in varia... >>
<< How to Replace NaN Values with Zeros in Pandas Dat...