2

I am trying to translate the first answer in Remove NaN row from X array and also the corresponding row in Y from Python to Julia 0.5.0 without importing numpy. I can replicate the "removing the NaNs" part with:

x1 = x[!isnan(x)]

but only using that reduces the 2D array down to 1D, and I don't want that. What would be the Julia equivalent of numpy.any in this case? Or if there isn't an equivalent, how can I keep my array 2D and delete entire rows that contain NaNs?

Community
  • 1
  • 1
LED
  • 129
  • 3
  • 6

1 Answers1

3

You can find rows that contain a NaN entry with any:

julia> A = rand(5, 4)
       A[rand(1:end, 4)] = NaN
       A
5×4 Array{Float64,2}:
   0.951717    0.0248771  0.903009    0.529702
   0.702505  NaN          0.730396    0.785191
 NaN           0.390453   0.838332  NaN
   0.213665  NaN          0.178303    0.0100249
   0.124465    0.363872   0.434887    0.305722

julia> nanrows = any(isnan(A), 2) # 2 means that we reduce over the second dimension
5×1 Array{Bool,2}:
 false
  true
  true
  true
 false

Then you can use the returned logical array as a mask into the first dimension, but we need to make it one-dimensional first:

julia> A[!vec(nanrows), :]
2×4 Array{Float64,2}:
 0.951717  0.0248771  0.903009  0.529702
 0.124465  0.363872   0.434887  0.305722
mbauman
  • 30,958
  • 4
  • 88
  • 123