如何从选定的pandas.df行开始for循环?

2024-10-02 16:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

用for循环处理pandas.df时,通常会遇到错误。当错误被删除后,我将不得不从数据帧的开头重新启动for循环。如何从错误位置启动for循环,避免重复运行。 例如:

senti = []
for i in dfs['ssentence']:
   senti.append(get_baidu_senti(i))

在上面的代码中,我试图通过api进行情感分析,并将其存储到一个列表中,但是api只输入GBK格式,而我的数据是utf-8编码的,所以通常会遇到如下错误:

UnicodeEncodeError: 'gbk' codec can't encode character '\u30fb' in position 14: illegal multibyte sequence

因此,我必须手动删除像'\u30fb'这样的特定项,并重新启动for循环。此时,列表“senti”已经包含了太多的数据,所以我不想放弃它们。如何改进for循环


Tags: 数据inapipandasdf列表forget
1条回答
网友
1楼 · 发布于 2024-10-02 16:22:46

如果您的API需要编码到GBK,那么只需使用'strict'(默认值)以外的错误处理程序编码到该编解码器

'ignore'将删除任何无法编码为GBK的代码点:

dfs['ssentence_encoded'] = dfs['ssentence'].str.encode('gbk', 'ignore')

参见Error Handlers section of Python's ^{} documentation

如果需要传入字符串,但只传入可以安全编码为GBK的字符串,那么我将创建一个适合^{} method的翻译映射:

class InvalidForEncodingMap(dict):
    def __init__(self, encoding):
        self._encoding = encoding
        self._negative = set()
    def __missing__(self, codepoint):
        if codepoint in self._negative:
            raise LookupError(codepoint)
        if chr(codepoint).encode(self._encoding, 'ignore'):
            # can be mapped, record as a negative and raise
            self._negative.add(codepoint)
            raise LookupError(codepoint)
        # map to None to remove
        self[codepoint] = None
        return None

only_gbk = InvalidForEncodingMap('gbk')
dfs['ssentence_gbk_safe'] = dfs['sentence'].str.translate(only_gbk)

InvalidForEncodingMap类在查找代码点时延迟地创建条目,因此只处理数据中实际存在的代码点。我仍然会保留map实例以供重用如果您需要多次使用它,那么它构建的缓存可以这样重用

相关问题 更多 >