티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Writing a pandas DataFrame to CSV file

CSV 파일에 Pandas 데이터프레임 쓰기

 문제 내용 

I have a dataframe in pandas which I would like to write to a CSV file.

저는 CSV 파일에 쓰고 싶은 Pandas의 데이터프레임을 가지고 있습니다.

 

I am doing this using:

다음을 사용하여 이 작업을 수행합니다.
df.to_csv('out.csv')

 

And getting the following error:

그리고 다음 오류가 발생합니다.
UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128)
  • Is there any way to get around this easily (i.e. I have unicode characters in my data frame)?
  • And is there a way to write to a tab delimited file instead of a CSV using e.g. a 'to-tab' method (that I don't think exists)?
- 이렇게 쉽게 이동할 수 있는 방법이 있습니까(즉, 데이터프레임에 유니코드 문자가 있습니다)?
- 그리고 CSV 대신에 탭으로 구분된 파일에 쓸 수 있는 방법이 있나요? 예를 들어, 'to-tab' 함수(존재하지 않는 것으로 생각됨)을 사용해서요.

 

 

 

 높은 점수를 받은 Solution 

To delimit by a tab you can use the sep argument of to_csv:

탭으로 구분하려면 to_csv의 sep 인수를 사용할 수 있습니다.
df.to_csv(file_name, sep='\t')

 

To use a specific encoding (e.g. 'utf-8') use the encoding argument:

특정 인코딩(예: 'utf-8')을 사용하려면 encoding 인수를 사용합니다.
df.to_csv(file_name, sep='\t', encoding='utf-8')

 

 

 가장 최근 달린 Solution 

If above solution not working for anyone or the CSV is getting messed up, just remove sep='\t' from the line like this:

위의 솔루션이 아무에게도 작동하지 않거나 CSV가 엉망이 되면 다음과 같이 줄에서 sep='\t'를 제거하십시오.
df.to_csv(file_name, encoding='utf-8')

 

 

출처 : https://stackoverflow.com/questions/16923281/writing-a-pandas-dataframe-to-csv-file

반응형
댓글
공지사항
최근에 올라온 글