Error using isnan

Hi,

I have trouble using the function isnan. I want to replace NaN value by 0. any help?
julia> a=[1 2 3; 4 5 NaN]
2×3 Array{Float64,2}:
1.0 2.0 3.0
4.0 5.0 NaN

julia> a[isnan(a)]=0
ERROR: MethodError: no method matching isnan(::Array{Float64,2})
Closest candidates are:
isnan(::BigFloat) at mpfr.jl:879
isnan(::Missing) at missing.jl:83
isnan(::Float16) at float.jl:530

Stacktrace:
[1] top-level scope at none:0

julia>

isnan is a function defined for scalar variables, you have to broadcast it to all elements of the array:

a[isnan.(a)] .= 0

or you can use the @. macro to dot everything for you:

@. a[isnan(a)] = 0
1 Like

Thanks very much it works

I think replace! is a much better fit for this purpose. It is so fast and has zero allocations.

julia> @btime replace!($a, NaN => 0)
  8.980 ns (0 allocations: 0 bytes)
2×3 Array{Float64,2}:
 1.0  2.0  3.0
 4.0  5.0  0.0
3 Likes