JuliaStats / TimeSeries.jl

Time series toolkit for Julia
Other
353 stars 69 forks source link

Construct TimeArray from NamedTuple #394

Closed scls19fr closed 5 years ago

scls19fr commented 5 years ago

Hello,

DataFrame from DataFrames.jl can be construct from NamedTuple

julia> using Dates

julia> using DataFrames

julia> data = (time=[DateTime(2018, 11, 21, 12, 0), DateTime(2018, 11, 21, 13, 0)], col1=[10.2, 11.2], col2=[20.2, 21.2])
(time = DateTime[2018-11-21T12:00:00, 2018-11-21T13:00:00], col1 = [10.2, 11.2], col2 = [20.2, 21.2])

julia> DataFrame(data)
2×3 DataFrame
│ Row │ time                │ col1    │ col2    │
│     │ DateTime            │ Float64 │ Float64 │
├─────┼─────────────────────┼─────────┼─────────┤
│ 1   │ 2018-11-21T12:00:00 │ 10.2    │ 20.2    │
│ 2   │ 2018-11-21T13:00:00 │ 11.2    │ 21.2    │

It will be nice if TimeArray could also be constructed like this.

julia> using TimeSeries

julia> TimeArray(data)

maybe passing name of datetime column should be considered (as a Symbol).

julia> TimeArray(data, timestamp=:time)

LibPQ uses this kind of mechanism https://invenia.github.io/LibPQ.jl/latest/index.html

Kind regards

PS : similar to https://github.com/dysonance/Temporal.jl/issues/33

scls19fr commented 5 years ago

Here is a possible implementation:

using Dates
using Test
using TimeSeries
import TimeSeries.TimeArray

data = (time=[DateTime(2018, 11, 21, 12, 0), DateTime(2018, 11, 21, 13, 0)], col1=[10.2, 11.2], col2=[20.2, 21.2], col3=[30.2, 31.2])

function TimeArray(data::NamedTuple; timestamp=:time)
    columns = (key for key in keys(data) if key != timestamp)
    dat = hcat((data[key] for key in columns)...)
    TimeArray(data[timestamp], dat, collect(columns))
end

ta = TimeArray(data)

println(ta)

@test size(ta) == (2, 3)
scls19fr commented 5 years ago

An other (related) feature would be to support DataStreams ie be able to support Data.stream!(result, TimeArray) and fetch!(TimeArray, result) like mentioned in https://invenia.github.io/LibPQ.jl/latest/index.html

iblislin commented 5 years ago

Could you send the code as a PR?