Stream: helpdesk (published)

Topic: ✔ Adding column to StructArray


view this post on Zulip Davi Sales Barreira (Feb 04 2024 at 01:03):

I'm new to the StructArray.jl package. Given that I have

s = StructArray((a=[1,2], b =[1,1]))
c = [5,5]

How can I then create a new StructArray with a column c, i.e. StructArray((a=[1,2], b =[1,1], c=[5,5])) ?

view this post on Zulip Davi Sales Barreira (Feb 04 2024 at 01:03):

In other words, how can I "add" a column to a StructArray?

view this post on Zulip jar (Feb 04 2024 at 01:08):

I feel like this should work.

julia> @set StructArray((;a=[1,2], b=[10,20])).c = [100,200]
ERROR: ArgumentError: Failed to assign properties (:c,) to object with properties (:a, :b).

view this post on Zulip Davi Sales Barreira (Feb 04 2024 at 01:10):

:/

view this post on Zulip Davi Sales Barreira (Feb 04 2024 at 01:11):

I can "brute force" by looping over the properties in the StructArray ,turning them into a namedtuple and then transforming the whole thing into a StructArray again.

view this post on Zulip Davi Sales Barreira (Feb 04 2024 at 01:11):

But this sounds inefficient... ?

view this post on Zulip aplavin (Feb 04 2024 at 01:23):

@jar just use @insert instead of @set :)

julia> using Accessors

julia> @insert s.c = [5, 5]
2-element StructArray(::Vector{Int64}, ::Vector{Int64}, ::Vector{Int64}) with eltype @NamedTuple{a::Int64, b::Int64, c::Int64}:
 (a = 1, b = 1, c = 5)
 (a = 2, b = 1, c = 5)

view this post on Zulip aplavin (Feb 04 2024 at 01:25):

@Davi Sales Barreira under the hood, @insert does exactly as you say: extracts columns as a namedtuple, adds another element there, and construct a new structarray. This is efficient, basically free!

view this post on Zulip Notification Bot (Feb 05 2024 at 13:06):

Davi Sales Barreira has marked this topic as resolved.


Last updated: Nov 06 2024 at 04:40 UTC