Python) Pandas read_csv 인코딩 확인하는 방법 소개

2022. 8. 30. 21:52분석 Python

728x90

파이썬에서 csv를 읽을 때 가장 큰 이슈 중에 하나는 가끔 인코딩이 안 맞아서 헤매는 경우가 많다.

이 경우 일반적으로 윈도우면 cp949 리눅스면 utf-8 대충 아는 식으로 하게 되면 대부분은 맞지만 특이한 것들이 나오는 경우가 있다.

이 방법은 리눅스에서만 가능할 것 같지만 소개한다.

리눅스

바로 다음 명령어를 사용하면 된다. (u.item이라는 파일이 있다고 가정)

file -i u.item

u.item: text/plain; charset=iso-8859-1

그럼 아래처럼 charset이 나오게 된다.

이걸 사용해서 읽을 때 인코딩으로 정해주면 된다.

import pandas as pd
df = pd.read_csv("u.item", sep="|", encoding="iso-8859-1")

아래는 utf-8로 바꾸는 명령어이다.

iconv -f ISO-8859-1 -t UTF-8 filename

윈도우

메모장으로 열어서 원하는 방식으로 바꾸는 방법...

꿀팁 끝

참고

https://stackoverflow.com/questions/30752973/encoding-issues-while-reading-importing-csv-file-in-python3-pandas

Encoding issues while reading/importing CSV file in Python3 Pandas

I am trying to read the Movie Lens dataset: http://files.grouplens.org/datasets/movielens/ml-100k/ using Pandas. I am using Python version 3.4 and I am following the tutorial given here" http://www.

stackoverflow.com

https://superuser.com/questions/123731/how-to-find-out-the-character-set-of-a-text-file

How to find out the character set of a text file

Is the a tool (mac or online) that can help me to find out the character set of a text file, and then convert it to utf-8 ?

superuser.com

728x90