Skip to content

Commit 347fba7

Browse files
committed
Fix minimum/maximum over dimensions with missing values
`v0 != v0` returns `missing` for missing values. Use the largest/smallest non-missing value to initialize the array. This is an inefficient approach. Faster alternatives would be to avoid using an initial value at all, and instead keep track of whether a value has been set in a separate mask; or to use `typemax`/`typemin` for types that support them.
1 parent ddf79a8 commit 347fba7

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

base/reducedim.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,10 @@ for (f1, f2, initval) in ((:min, :max, :Inf), (:max, :min, :(-Inf)))
144144
# otherwise use the min/max of the first slice as initial value
145145
v0 = mapreduce(f, $f2, A1)
146146

147-
# but NaNs need to be avoided as initial values
147+
# but missings and NaNs need to be avoided as initial values
148+
if ismissing(v0) && !all(ismissing, A)
149+
v0 = mapreduce(f, $f2, skipmissing(A))
150+
end
148151
v0 = v0 != v0 ? typeof(v0)($initval) : v0
149152

150153
T = _realtype(f, promote_union(eltype(A)))

test/reduce.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,14 @@ end
325325
@test maximum(Vector(Int16(1):Int16(100))) === Int16(100)
326326
@test maximum(Int32[1,2]) === Int32(2)
327327

328+
@testset "minimum/maximum over dims with missing (#35308)" begin
329+
x = [1 missing; 2 missing]
330+
@test isequal(minimum(x, dims=1), reshape([1, missing], 1, :))
331+
@test isequal(maximum(x, dims=1), reshape([2, missing], 1, :))
332+
@test isequal(minimum(x, dims=2), reshape([missing, missing], :, 1))
333+
@test isequal(maximum(x, dims=2), reshape([missing, missing], :, 1))
334+
end
335+
328336
A = circshift(reshape(1:24,2,3,4), (0,1,1))
329337
@test extrema(A,dims=1) == reshape([(23,24),(19,20),(21,22),(5,6),(1,2),(3,4),(11,12),(7,8),(9,10),(17,18),(13,14),(15,16)],1,3,4)
330338
@test extrema(A,dims=2) == reshape([(19,23),(20,24),(1,5),(2,6),(7,11),(8,12),(13,17),(14,18)],2,1,4)

0 commit comments

Comments
 (0)