Indexing in Daru has grown more powerful. Here's a glimpse. Enjoy!
require 'daru'
A new class of index got added to Daru to handle indexing which can be categorical. This is basically how it works.
idx = Daru::CategoricalIndex.new [:a, 1, :a, 1, :c]
dv = Daru::Vector.new 'a'..'e', index: idx
Get elements with single category.
dv[:a]
Retrive elements by multiple categories.
dv[:a, 1]
Get elements by position using #at
.
dv.at 1
You can get multiple element as a vector if you specify more than one position.
dv.at 0, 1, 2
Note: You can also use #[]
to get elements by position only if that position is not a index.
Get elements by single position.
dv[3]
Get elements by multiple positions.
dv[0, 3]
Change values at certain indexes using []=
dv[:a] = 20
dv
Change values at certain positions using at_set
dv.at_set [0, 1], 100
dv
Overall all Index classes API are improved. Everyclass respond to multiple indexes, positional index, give proper error messages, etc.
Here are few examples:
idx = Daru::Index.new [:a, :b, :c, :d]
dv = Daru::Vector.new 1..4, index: idx
Retrive values by index or positions.
Note: When the value is both a valid index and a valid position, it will be treated as index value.
dv[:a, :b]
Retive values by positions.
dv.at 0, 1
Set values by index or positions.
Note: When value is both a valid index and a valid position, it will be treated as index value.
dv[:a, :b] = 'x'
dv
Set values in vector by positions.
dv.at_set [0, 2], 'y'
dv
idx = Daru::MultiIndex.from_tuples [
[:a,:one,:bar],
[:a,:one,:baz],
[:a,:two,:bat],
[:b,:one,:bar],
[:b,:two,:baz],
]
dv = Daru::Vector.new 1..5, index: idx
Retrive values by index or positions.
Note: When value is both a valid index or position then value will be treated as index rather position.
Partial Index
dv[:a]
On mentioning complete index, one will get the value at that index
dv[:a, :one, :bar]
Retrive values by positions
dv.at 0, 1, 2
Assign values by index or positions
dv[:a, :one] = 'x'
dv
Assign values by positions
dv.at_set [0, 1, 2], 'z'
dv