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