错误 'float' 对象没有属性 'encode' 将应用(unidecode)应用于数据帧的 str 列时

Error 'float' object has no attribute 'encode' when using apply(unidecode) to a dataframe's column of str

我正在尝试使用 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(州)和 cidade(城市)[=13 的列中的所有元素=]

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

如果有人也能帮助我在列表理解中编写这个 for 循环,那就太好了,我试过了,但没有成功。此切片位于 class 内,我希望尽可能保持最干净和最简单。

可能是因为运算符的优先级。 or 的优先级高于 and

所以在表达式中加上括号可能会有所帮助。

if (col == 'estado' or col == 'cidade') and (df_[col] is not None and isinstance(df_[col], str)):

其次。而不是 for 循环。定义谓词并将谓词传递给应用函数

def pred(x):
    # code

df_.apply(pred, axis=1)

郑重声明,我解决了我的问题"forcing" 我所有的系列元素都到 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)

我认为这不是更明智的解决方案,但我一直在努力,我选择了这个解决方案,因为我的最后期限很短。

谢谢大家的帮助!