Convert Array of NamedTuple to Arrays in Julia

Viewed 245

I have an Array of NamedTuple I read out of an hdf5 file in Julia. It has names X, Y, and Z. Is there an succinct way to convert this to three arrays containing the values of X, Y, and Z respectively?

typeof(science_h5["/Nav/Position"][:])

Array{NamedTuple{(:X, :Y, :Z),Tuple{Float32,Float32,Float32}},1}
1 Answers

You can use Tables.columntable from Tables.jl:

julia> a = [(X=i, Y=i+1, Z=i+2) for i in 1:5]
5-element Vector{NamedTuple{(:X, :Y, :Z), Tuple{Int64, Int64, Int64}}}:
 (X = 1, Y = 2, Z = 3)
 (X = 2, Y = 3, Z = 4)
 (X = 3, Y = 4, Z = 5)
 (X = 4, Y = 5, Z = 6)
 (X = 5, Y = 6, Z = 7)

julia> Tables.columntable(a)
(X = [1, 2, 3, 4, 5], Y = [2, 3, 4, 5, 6], Z = [3, 4, 5, 6, 7])

If you want to only use Julia Base you could do:

julia> X, Y, Z = [getindex.(a, i) for i in 1:3]
3-element Vector{Vector{Int64}}:
 [1, 2, 3, 4, 5]
 [2, 3, 4, 5, 6]
 [3, 4, 5, 6, 7]

or

julia> X, Y, Z = [getproperty.(a, i) for i in (:X, :Y, :Z)]
3-element Vector{Vector{Int64}}:
 [1, 2, 3, 4, 5]
 [2, 3, 4, 5, 6]
 [3, 4, 5, 6, 7]
Related