【发布时间】:2017-03-01 07:05:44
【问题描述】:
我创建了一个函数来清除数据框中字符串中的任何 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”对象。
【问题讨论】:
标签: python pandas try-except