我正在尝试使用for循环从数据框的列中删除重音符号,但是我不断收到错误消息“ float对象没有属性编码”,它是一个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是熊猫数据框,在此步骤之前,它从CSV文件接收数据
col从数据框中读取列的名称
df_ [col]应该读取名为estado(州)和cidade(城市)
的列中的所有元素。我只想删除这两列中的所有重音。
[如果有人也可以帮助我在列表理解中编写此for循环会很棒,我尝试了但没有用。该切片位于类的内部,我想尽可能保持最简洁。
这可能是因为运算符的优先级。or
的优先级高于and
。
因此将括号放在表达式中可能会有所帮助。
if (col == 'estado' or col == 'cidade') and (df_[col] is not None and isinstance(df_[col], str)):
第二。而不是for循环。定义谓词并将谓词传递给apply函数
def pred(x):
# code
df_.apply(pred, axis=1)
仅出于记录目的,我解决了将所有系列元素“强制”插入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)
我认为这不是更明智的解决方案,但我一直在努力,由于我的截止日期很短,所以选择了此解决方案。
感谢所有帮助人员!