logo

How to Replace NaN with 0 in Julia DataFrames 📂Julia

How to Replace NaN with 0 in Julia DataFrames

Overview

The method of replacing with a specific value is inconvenient because it changes one column at a time, and when dealing with NaN throughout the dataframe, it seems more practical to use a better trick.

Code

julia> df = DataFrame(rand(1:9,3,3), :auto) ./ DataFrame(rand(0:1,3,3), :auto)
3×3 DataFrame
 Row │ x1       x2       x3      
     │ Float64  Float64  Float64
─────┼───────────────────────────
   1 │     5.0    Inf        7.0
   2 │   Inf        8.0    Inf
   3 │     4.0      1.0      4.0

For instance, if you want to replace Inf with 0 in the dataframe above, you can do it in just one line as follows.

julia> ifelse.(isinf.(df), 0, df)
3×3 DataFrame
 Row │ x1       x2       x3      
     │ Float64  Float64  Float64
─────┼───────────────────────────
   1 │     5.0      0.0      7.0
   2 │     0.0      8.0      0.0
   3 │     4.0      1.0      4.0

Of course, if you replace isinf with isnan in ifelse.(isinf.(df), 0, df), you can handle NaN, and you can change 0 to send to any value you prefer.

Full Code

using DataFrames, Random
Random.seed!(0)

df = DataFrame(rand(1:9,3,3), :auto) ./ DataFrame(rand(0:1,3,3), :auto)
ifelse.(isinf.(df), 0, df)

See Also

Environment

  • OS: Windows
  • julia: v1.6.3