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

时间:2015-03-02 19:01:58

标签: python arrays string mixed

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

1 个答案:

答案 0 :(得分: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.