Skip to content

Commit 11c4625

Browse files
committed
Allow two-dimensional getindex for TTree
1 parent a4cbfcb commit 11c4625

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/ttree.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,16 @@
1010
`TTree` is an on-disk data structure, iteration over single elements is *very*
1111
inefficient.
1212
13+
Even though `TTree` is semantically a vector over the tree entries, a two
14+
dimensional `getindex(tree::TTree, entries, branches)` is defined for
15+
convenience. So you may use, e.g.:
16+
17+
```julia
18+
tree[1:5, (:branch1, :branch2)]
19+
tree[:, [:branch1, :branch2]]
20+
tree[[1,4,7,10], ["branch1", "branch2"]]
21+
```
22+
1323
Limitations: Write access is not implemented yet.
1424
"""
1525
struct TTree <: AbstractVector{NamedTuple}
@@ -52,6 +62,14 @@ Base.getindex(tree::TTree, i::Integer) = first(tree[i:i])
5262

5363
Base.getindex(tree::TTree, ::Colon) = getindex(tree, eachindex(tree))
5464

65+
Base.getindex(tree::TTree, idxs, col::Symbol) = getproperty(tree, col)[idxs]
66+
67+
function Base.getindex(tree::TTree, idxs, cols::Union{Tuple,AbstractArray})
68+
colnames = map(Symbol, (cols...,))
69+
colvalues = map(c -> tree[idxs, c], colnames)
70+
Table(NamedTuple{colnames}(colvalues))
71+
end
72+
5573

5674
Tables.istable(::Type{TTree}) = true
5775

test/test_testfiles.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,5 +45,9 @@ using TypedTables
4545
@test convert(Array, tree.Jet_E) == tree.Jet_E[:]
4646

4747
@test Table(tree) == tree[:]
48+
49+
@test tree[1:5, (:Jet_Px, :Jet_Py, :Jet_Pz)] isa Table{<:NamedTuple{(:Jet_Px, :Jet_Py, :Jet_Pz)}}
50+
@test tree[:, [:Jet_Px, :Jet_Py, :Jet_Pz]] isa Table{<:NamedTuple{(:Jet_Px, :Jet_Py, :Jet_Pz)}}
51+
@test tree[[2, 4, 7, 11], ["Jet_Px", "Jet_Py", "Jet_Pz"]] isa Table{<:NamedTuple{(:Jet_Px, :Jet_Py, :Jet_Pz)}}
4852
end
4953
end

0 commit comments

Comments
 (0)