【问题标题】:how to start a for loop from a chosen row of pandas.df?如何从选定的 pandas.df 行开始一个 for 循环?
【发布时间】:2019-02-12 14:22:16
【问题描述】:

使用 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 循环?

【问题讨论】:

  • 编码时为什么不指定错误处理程序?
  • @MartijnPieters 我要发布GBK格式的数据,编码时如何写错误处理程序?我唯一能想到的就是删除错误字符。
  • 这就是错误处理程序可以为您做的:.encode('gbk', 'ignore') 跳过无法编码的代码点。
  • 您确定您的数据被编码为 UTF8 吗?您似乎有字符串值,因此 Unicode 值已经从字节解码(UTF-8 意味着您有二进制编码数据)。

标签: python pandas for-loop utf-8 gbk


【解决方案1】:

如果您的 API 需要编码为 GBK,则只需使用除 'strict'(默认值)之外的错误处理程序编码为该编解码器。

'ignore' 将丢弃所有无法编码为 GBK 的代码点:

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

请参阅Error Handlers section of Python's codecs documentation

如果您需要传入字符串,但只能传入可以安全编码为 GBK 的字符串,那么我会创建一个适合 str.translate() 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 类在查找代码点时懒惰地创建条目,因此仅处理数据中实际存在的代码点。如果您需要多次使用它,我仍然会保留地图实例以供重复使用,它建立的缓存可以这样重复使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多