【问题标题】:Encoding error using df.to_csv()使用 df.to_csv() 编码错误
【发布时间】:2016-01-08 14:47:46
【问题描述】:

我正在尝试将 Twits 中的信息(screen_name、created_at 和 text)保存到 pandas DataFrame,然后将 DataFrame 保存为 csv 文件。

我收到编码错误

import tweepy
from tweepy import OAuthHandler

consumer_key = 'bla'
consumer_secret = 'bla'
access_token = 'bla'
access_secret = 'bla'
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

import pandas as pd
import numpy as np
import datetime
import sys

encoding = sys.stdout.encoding or 'utf-8'
columns = ['Screen_Name', 'Time_Stamp', 'Tweet']
todays_date = datetime.datetime.now().date()
tweetDF = pd.DataFrame(columns=columns)

for tweet in tweepy.Cursor(api.search, q="manhattan", lang="en").items(10):
    lenDF = len(tweetDF)
    tweetDF.loc[lenDF] = [tweet.user.screen_name, tweet.created_at, tweet.text]

tweetDF.to_csv("C:/tweetDF")

这里的错误:

UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-11-c0aa5e7ee620> in <module>()

---> 34 tweetDF.to_csv("C:/tweetDF")

C:\Anaconda\lib\site-packages\pandas\core\frame.pyc in to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, quoting, quotechar, line_terminator, chunksize, tupleize_cols, date_format, doublequote, escapechar, decimal, **kwds)
   1187                                      escapechar=escapechar,
   1188                                      decimal=decimal)
-> 1189         formatter.save()
   1190 
   1191         if path_or_buf is None:

C:\Anaconda\lib\site-packages\pandas\core\format.pyc in save(self)
   1465 
   1466             else:
-> 1467                 self._save()
   1468 
   1469         finally:

C:\Anaconda\lib\site-packages\pandas\core\format.pyc in _save(self)
   1565                 break
   1566 
-> 1567             self._save_chunk(start_i, end_i)
   1568 
   1569     def _save_chunk(self, start_i, end_i):

C:\Anaconda\lib\site-packages\pandas\core\format.pyc in _save_chunk(self, start_i, end_i)
   1592                                         quoting=self.quoting)
   1593 
-> 1594         lib.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer)
   1595 
   1596 # from collections import namedtuple

pandas\lib.pyx in pandas.lib.write_csv_rows (pandas\lib.c:17992)()

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2666' in position 7: ordinal not in range(128)

我尝试了各种编码增强功能,但都没有成功

【问题讨论】:

  • 你用的是什么版本的 Python?
  • @MattDMo - 2.7 版
  • 这篇文章可能需要 Python3 的更新答案。

标签: python csv encoding utf-8 dataframe


【解决方案1】:

我找到了解决方法并愿意分享:

tweetDF.to_csv("C:/tweetDF", sep='\t', encoding = 'utf-8')

【讨论】:

  • 你能解释一下为什么这解决了这个问题吗?我不知道为什么这与原始问题相比有效。使用此函数时,编码默认为“utf-8”,如该函数pandas.pydata.org/docs/reference/api/… 的原始文档中所述。
猜你喜欢
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多