使用df.to_csv()出现编码错误

9

我正在尝试将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)

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


1
你使用的Python版本是什么? - MattDMo
@MattDMo - 版本2.7 - Toly
1
这篇文章可能需要一个Python3的更新答案。 - user12217470
1个回答

8
我找到了解决方法并想分享:

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

你能解释一下为什么这个解决方案有效吗?相比原来的问题,我不知道为什么这个方法可以起作用。在使用此函数时,默认编码已经是“utf-8”,正如此函数的原始文档 https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html 中所述。 - user12217470

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接