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

Python try/except出现问题,尝试在可能的情况下将字符串转换为数据帧中的整数,python,pandas,try-except,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_o

我创建了一个函数来清除数据框中字符串中的任何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

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

column.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

考虑
pd.DataFrame
df

df = pd.DataFrame(dict(A=[1, '2', '_', '4']))
df['A'] = pd.to_numeric(df['A'], 'coerce').combine_first(df['A'])

您想使用函数
pd.\u numeric

注意
pd.to_numeric
对标量和
pd.Series
进行操作。它不在
pd.DataFrame上运行


使用参数
errors='concurve'
在您可以的地方获取数字,并在其他地方使用参数
NaN

pd.to_numeric(df['A'], 'coerce')

0    1.0
1    2.0
2    NaN
3    4.0
Name: A, dtype: float6
或者,尽可能地获取数字,以及其他地方已有的数据

pd.to_numeric(df['A'], 'coerce').combine_first(df['A'])

0    1
1    2
2    _
3    4
Name: A, dtype: object
然后,您可以将其分配回您的
df

df = pd.DataFrame(dict(A=[1, '2', '_', '4']))
df['A'] = pd.to_numeric(df['A'], 'coerce').combine_first(df['A'])
工作原理如下:

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

在函数中使用try/except,并将该函数与


谢谢你的帮助。不幸的是,这将返回一个int对象而不是df。如果您告诉代码返回int(row)
,我将它从您的初始代码中删除。。