如何导入包含混合浮点数和非数字字符串的数组,并将字符串转换为零

how do I import an array with mixed floats and non-numeric strings, with strings converted to zeros

我有一个类似于 [1.124, 5.152, 6.235, NaN, 5.124, Infinity] 的数组。我想将其导入为 [1.124, 5.152, 6.235, 0, 5.124, 0]。我该怎么做?

基于 NaN 和 Inf 的过滤器:

print([float(ele) if ele not in {"NaN","Infinity"} else 0 for ele in arr])

如果你使用的是 numpy。

arr = np.genfromtxt("a.txt", dtype=float,delimiter=",")
print(arr)
arr[~np.isfinite(arr)] = 0
print(arr)
[ 1.124  5.152  6.235    nan  5.124    inf]
[ 1.124  5.152  6.235  0.     5.124  0.