在Julia中将类型数组{Union{Missing,Float64},1}转换为数组{Float64,1}

在Julia中将类型数组{Union{Missing,Float64},1}转换为数组{Float64,1},julia,Julia,我有一个浮点数组,其中缺少一些值,因此它的类型是array{Union{missing,Float64},1}。是否有命令将未丢失的部分转换为数组{Float64,1}?以下是三种解决方案,按优先顺序排列(感谢@BogumilKaminski提供了第一种解决方案): f1lazy使用skipmissing(对迭代非常有用)加载数组,然后通过collect构建数组 f2对循环使用,但可能比f1慢,因为最终数组长度没有提前计算 f3使用广播,并在此过程中分配临时资源,因此可能是三者中速度最慢的 我们

我有一个浮点数组,其中缺少一些值,因此它的类型是
array{Union{missing,Float64},1}
。是否有命令将未丢失的部分转换为
数组{Float64,1}

以下是三种解决方案,按优先顺序排列(感谢@BogumilKaminski提供了第一种解决方案):

f1
lazy使用
skipmissing
(对迭代非常有用)加载数组,然后通过
collect
构建数组

f2
对循环使用
,但可能比
f1
慢,因为最终数组长度没有提前计算

f3
使用广播,并在此过程中分配临时资源,因此可能是三者中速度最慢的

我们可以用一个简单的基准来验证上述内容:

using BenchmarkTools
x = Array{Union{Missing,Float64}}(undef, 100);
inds = unique(rand(1:100, 50));
x[inds] = randn(length(inds));
@btime f1($x);
@btime f2($x);
@btime f3($x);
导致:

julia> @btime f1($x);
  377.186 ns (7 allocations: 1.22 KiB)

julia> @btime f2($x);
  471.204 ns (8 allocations: 1.23 KiB)

julia> @btime f3($x);
  732.726 ns (6 allocations: 4.80 KiB)

我通常会编写
skipmissing(x)
,返回一个惰性包装,并编写
collect(skipmissing(x))
来具体化一个数组。这应该比
h
快。是的,那好多了。当我下一次站在计算机前时,我将添加该解决方案和基准测试
julia> @btime f1($x);
  377.186 ns (7 allocations: 1.22 KiB)

julia> @btime f2($x);
  471.204 ns (8 allocations: 1.23 KiB)

julia> @btime f3($x);
  732.726 ns (6 allocations: 4.80 KiB)