首页 > 解决方案 > 使用 apply(unidecode) 到数据帧的 str 列时,错误“float”对象没有属性“encode”

问题描述

我正在尝试使用 for 循环从数据框的列中删除重音符号,但我不断收到错误消息“float object has no attribute encode”并且它是一个 str 列。最有趣的是,我在代码的两点应用了这个循环,它只在第二点识别错误。

df_ = df_target.copy()

for col in df_:
    if col == 'estado' or col == 'cidade' and (df_[col] is not None and isinstance(df_[col], str)):
        print(df_[col].head(100))
        df_[col] = df_[col].apply(unidecode)

df_target是一个 pandas 数据框,在这一步之前,它从 CSV 文件中接收数据

col从数据框中读取列的名称

df_[col] 应该读取名为estado (state) 和cidade (city)的列中的所有元素

我只想从这两列中删除所有重音。

如果有人也可以帮助我在列表理解中编写这个 for 循环会很棒,我试过但没有奏效。这个切片在一个类中,我想尽可能保持最干净和最简单。

标签: pythonpython-3.xpandasoopencode

解决方案


只是为了记录,我解决了我的问题“强制”我的所有系列元素到 str。

        for col in df_target:
        if col == 'estado' or col == 'cidade':
            df_target[col] = df_target[col].astype(str)
            df_target[col] = df_target[col].apply(unidecode)

我认为这不是更聪明的解决方案,但我很挣扎,我选择了这个解决方案,因为我的截止日期很短。

感谢所有帮助的家伙!


推荐阅读