更改 Pandas 数据帧类型时的异常处理

lma*_*999 5 python pandas

我有一个带有单列字符串的 Pandas 数据框。我想将列数据转换为浮动。由于格式的原因,某些值无法转换为浮点数。我想从结果中省略这些“非法字符串”,只提取可以合法地重新转换为浮点数的值。起始数据:

test=pd.DataFrame()
test.loc[0,'Value']='<3'
test.loc[1,'Value']='10'
test.loc[2,'Value']='Detected'
test.loc[3,'Value']=''
Run Code Online (Sandbox Code Playgroud)

所需的输出仅包含可以重新转换为浮点数的字符串(在本例中为 10):

cleanDF=test['Value'].astype(float)
cleanDF
0    10
Name: Value, dtype: float64
Run Code Online (Sandbox Code Playgroud)

当然,这会在浮点转换的非法字符串上按预期抛出错误:

ValueError: could not convert string to float: <3
Run Code Online (Sandbox Code Playgroud)

如果数据框很大并且“值”中包含许多非法字符串,是否有一种简单的方法可以解决这个问题?

谢谢。

Phi*_*hil 5

您可以尝试使用 DataFrame 的apply. 编写一个包含异常处理程序的函数并将其应用于 DataFrame。

def test_apply(x):
    try:
        return float(x)
    except ValueError:
        return None

cleanDF = test['Value'].apply(test_apply).dropna()
Run Code Online (Sandbox Code Playgroud)

  • 这是相当低效的;更好的是:``test['Value'].convert_objects(convert_numeric=True).dropna()`` (2认同)