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

Issues with try/except, attempting to convert strings to integers in pandas data frame where possible

我创建了一个函数来清除数据框中字符串中的任何 HTML code/tags。该函数从数据框中获取每个值,使用 remove_html 函数对其进行清理,并且 returns 是一个干净的 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 语句,函数 return 是一个干净的 df,其中整数是字符串。所以它只是 try/except 声明似乎是一个问题。我以多种方式尝试了 try/except 语句,其中 none return 一个 df。例如,当前代码 return 是一个 '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

考虑 pd.DataFrame df

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

您想使用函数 pd.to_numeric...

pd.to_numeric 对标量和 pd.Series 进行运算。它不适用于 pd.DataFrame
还有
使用参数 errors='coerce' 尽可能获取数字,在其他地方使用 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['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 并将该函数与 DataFrame.applymap()

一起使用
df = pd.DataFrame([['a','b','1'],
                   ['2','c','d'],
                   ['e','3','f']])
def foo(thing):
    try:
        return int(thing)
    except ValueError as e:
        return thing

>>> df[0][2]
'e'
>>> df[0][1]
'2'
>>> df = df.applymap(foo)
>>> df[0][2]
'e'
>>> df[0][1]
2
>>>