python - try/except 的问题,尝试尽可能将 pandas 数据框中的字符串转换为整数

标签 python pandas try-except

我创建了一个函数来清除数据框中字符串中的所有 HTML 代码/标签。该函数从数据框中获取每个值,使用 remove_html 函数对其进行清理,并返回一个干净的 df。将数据框转换为字符串值并清理后,我试图尽可能将数据框中的值转换回整数。我试过 try/except 但没有得到我想要的结果。这是我目前拥有的:

def clean_df(df):
    df = df.astype(str)
    list_of_columns = list(df.columns)
    for col in list_of_columns:
        column = []
        for row in list(df[col]):
            column.append(remove_html(row))
            try:
                return int(row)
            except ValueError:
                pass

        del df[col]

        df[col] = column

    return df

如果没有 try/except 语句,该函数将返回一个干净的 df,其中整数是字符串。所以它只是 try/except 语句似乎是一个问题。我以多种方式尝试了 try/except 语句,但没有一个返回 df。例如,当前代码返回一个“int”对象。

最佳答案

columm.append 插入 try:

for col in list_of_columns:
    column = []
    for row in list(df[col]):
        try:
            column.append(remove_html(row))
        except ValueError:
            pass

    del df[col]

    df[col] = column

return df

关于python - try/except 的问题,尝试尽可能将 pandas 数据框中的字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40134811/

相关文章:

python try/except/else 递归

python - 在 PyTorch 中将张量向量化分配给切片

python - 如何删除 pandas 数据框中具有重复列值的行?

pandas - 本地化 pandas 中的时间戳

python - 将一些数值列映射到 Pandas 中的新元组列中

如果最终返回值,则不会引发 python 异常

python - 使用 Python 请求模块时尝试/除外

python - 在python中集成多个字典(大数据)

python - urllib 打开文件太多

python - 当元素包含 numpy 数组时,无法测试 python 列表元素成员资格