try/except的问题,尝试在可能的情况下将字符串转换为pandas数据框中的整数

RF_*_*_PY 5 python pandas try-except

我创建了一个函数来清理数据框中字符串的任何HTML代码/标记.该函数从数据框中获取每个值,使用remove_html函数清除它,并返回一个干净的df.在将数据帧转换为字符串值并清理它之后,我试图在可能的情况下将数据帧中的值转换回整数.我试过尝试/除了但没有得到我想要的结果.这就是我现在所拥有的:

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
Run Code Online (Sandbox Code Playgroud)

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

RF_*_*_PY 0

工作原理如下:

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]):
        try:
            column.append(int(remove_html(row)))
        except ValueError:
            column.append(remove_html(row))

    del df[col]

    df[col] = column

return df
Run Code Online (Sandbox Code Playgroud)