Home > database >  How to convert array of named tuples to named tuple of arrays?
How to convert array of named tuples to named tuple of arrays?

Time:11-01

If I have an array of named tuples:

[(a=1,b=1),
 (a=2,b=4),
 (a=3,b=9)]

And I would like a named tuple of arrays:

(a=[1,2,3], b=[1,4,9])

Is there a simple way to do that? Ideally in a lazy way or without copying.

CodePudding user response:

This can be achieved with LazyArrays.jl.

julia> using LazyArrays

julia> xs = fill((a=1,b=2), 1024);

julia> using BenchmarkTools

julia> @btime (a = LazyArray(@~ getproperty.($xs, :a)), b = LazyArray(@~ getproperty.($xs, :b)))
  10.988 ns (2 allocations: 32 bytes)

julia> (a = LazyArray(@~ getproperty.(xs, :a)), b = LazyArray(@~ getproperty.(xs, :b))) == (a=getproperty.(xs, :a), b=getproperty.(xs, :b))
true
  • Related