Skip to content

Commit 3f31a80

Browse files
committed
Add functions to README to transform the DataFrame into a TimeArray
1 parent b9d5058 commit 3f31a80

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

README.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,5 +144,55 @@ If you just want to do it once, you may use the argument `use_readlines` of the
144144
df1 = rdb(ids = "AMECO/ZUTN/EA19.1.0.0.0.ZUTN", use_readlines = true);
145145
```
146146

147+
## Transform the `DataFrame` object into a `TimeArray` object (Julia ≥ 0.7)
148+
For some analysis, it is more convenient to have a `TimeArray` object instead of a `DataFrame` object. To transform
149+
it, you can use the following functions :
150+
```julia
151+
using DBnomics
152+
using DataFrames
153+
using TimeSeries
154+
155+
function to_namedtuples(x::DataFrames.DataFrame)
156+
nm = names(x);
157+
vl = [x[:, col] for col in names(x)];
158+
159+
nm = tuple(nm...);
160+
vl = tuple(vl...);
161+
162+
NamedTuple{nm}(vl)
163+
end
164+
165+
function to_timeseries(
166+
x::DataFrames.DataFrame,
167+
index = :period, variable = :series_code, value = :value
168+
)
169+
x = unstack(x, index, variable, value);
170+
x = to_namedtuples(x);
171+
x = TimeArray(x, timestamp = index);
172+
x
173+
end
174+
175+
rdb("IMF", "CPI", mask = "M.DE+FR.PCPIEC_WT")
176+
#> 570×13 DataFrame. Omitted printing of 9 columns
177+
#> │ Row │ @frequency │ dataset_code │ dataset_name │ indexed_at │
178+
#> │ │ String │ String │ String │ TimeZones.ZonedDateTime │
179+
#> ├─────┼────────────┼──────────────┼────────────────────────────┼───────────────────────────────┤
180+
#> │ 1 │ monthly │ CPI │ Consumer Price Index (CPI) │ 2019-05-18T02:48:55.708+00:00 │
181+
#> │ 2 │ monthly │ CPI │ Consumer Price Index (CPI) │ 2019-05-18T02:48:55.708+00:00 │
182+
#> │ ... │ ... │ ... │ ... │ ... │
183+
#> │ 569 │ monthly │ CPI │ Consumer Price Index (CPI) │ 2019-05-18T02:48:55.708+00:00 │
184+
#> │ 570 │ monthly │ CPI │ Consumer Price Index (CPI) │ 2019-05-18T02:48:55.708+00:00 │
185+
186+
to_timeseries(rdb("IMF", "CPI", mask = "M.DE+FR.PCPIEC_WT"))
187+
#> 291×2 TimeArray{Union{Missing, Float64},2,Date,Array{Union{Missing, Float64},2}} 1995-01-01 to 2019-03-01
188+
#> │ │ M.DE.PCPIEC_WT │ M.FR.PCPIEC_WT │
189+
#> ├────────────┼────────────────┼────────────────┤
190+
#> │ 1995-01-01 │ missing │ 20.0 │
191+
#> │ 1995-02-01 │ missing │ 20.0 │
192+
#> │ ... │ ... │ ... │
193+
#> │ 2019-02-01 │ 30.1 │ 25.8 │
194+
#> │ 2019-03-01 │ 30.1 │ 25.8 │
195+
```
196+
147197
## P.S.
148198
Visit <a href="https://db.nomics.world/" target="_blank">https://db.nomics.world/</a> :bar_chart: !

0 commit comments

Comments
 (0)