更新时间:2022-05-27 22:04:39
您可以使用以下列表理解:
You could use the following list comprehension:
import numpy as np
[[0 if np.isnan(j) else j for j in i] for i in l_of_l]
# [[1, 2, 3], [0, 0, 0], [3, 4, 5]]
如果您想避免导入 numpy
,尽管数据表明您应该使用它,则实际上可以执行以下操作:
If you want to avoid importing numpy
, though the data suggests that you should be using it, you could actually do the same with:
[[0 if j!=j else j for j in i] for i in l_of_l]
# [[1, 2, 3], [0, 0, 0], [3, 4, 5]]
根据定义,NaN
永远不等于自己
This works as by definition NaNs
are never equal to themselves
或直接构建一个 numpy
数组并使用 nan_to_num
:
Or directly build a numpy
array and use nan_to_num
:
np.nan_to_num(np.array(l_of_l))
array([[1., 2., 3.],
[0., 0., 0.],
[3., 4., 5.]])