dataframe - Julia DataFrames 等效于 pandas pct_change()
问题描述
目前,我已经编写了以下用于百分比变化计算的函数:
function pct_change(input::AbstractVector{<:Number})::AbstractVector{Number}
result = [NaN]
for i in 2:length(input)
push!(result, (input[i] - input[i-1])/abs(input[i-1]))
end
return result
end
这按预期工作。但是想知道 Julia DataFrames 是否有类似于 pandas 的内置函数pct_change
可以直接使用?或者我可以对上面的功能做出任何其他更好的方法或改进?
解决方案
This is a very specific function and is not provided in DataFrames.jl, but rather TimeSeries.jl. Here is an example:
julia> using TimeSeries, Dates
julia> ta = TimeArray(Date(2018, 1, 1):Day(1):Date(2018, 12, 31), 1:365);
julia> percentchange(ta);
(there are some more options to what should be calculated)
The drawback is that it accepts only TimeArray
objects and that it drops periods for which percent change cannot be calculated (as they are retained in Python).
If you want your custom definition consider denoting the first value as missing
rather than NaN
, as missing
. Also your function will not produce the most accurate representation of the numbers (e.g. if you wanted to use BigFloat
or exact calculations using Rational
type they will be converted to Float64
). Here are example alternative function implementations that avoid these problems:
function pct_change(input::AbstractVector{<:Number})
res = @view(input[2:end]) ./ @view(input[1:end-1]) .- 1
[missing; res]
end
or
function pct_change(input::AbstractVector{<:Number})
[i == 1 ? missing : (input[i]-input[i-1])/input[i-1] for i in eachindex(input)]
end
And now you have in both cases:
julia> pct_change(1:10)
10-element Array{Union{Missing, Float64},1}:
missing
1.0
0.5
0.33333333333333326
0.25
0.19999999999999996
0.16666666666666674
0.1428571428571428
0.125
0.11111111111111116
julia> pct_change(big(1):10)
10-element Array{Union{Missing, BigFloat},1}:
missing
1.0
0.50
0.3333333333333333333333333333333333333333333333333333333333333333333333333333391
0.25
0.2000000000000000000000000000000000000000000000000000000000000000000000000000069
0.1666666666666666666666666666666666666666666666666666666666666666666666666666609
0.1428571428571428571428571428571428571428571428571428571428571428571428571428547
0.125
0.111111111111111111111111111111111111111111111111111111111111111111111111111113
julia> pct_change(1//1:10)
10-element Array{Union{Missing, Rational{Int64}},1}:
missing
1//1
1//2
1//3
1//4
1//5
1//6
1//7
1//8
1//9
with proper values returned.
推荐阅读
- asynchronous - 当 typeahead 的值已经异步时,Typeahead 会跳过异步请求
- javascript - Chart.js 标签 - 水平条形图的 Y 轴上需要两个标签
- rust - Rust:在`impl`中的函数中返回对成员变量的引用
- c - C - 哈希表键的链表
- python-3.x - 使用 LXML.HTML 和 Xpath 进行 WebScraping
- java - 如何在不重新启动 Activity 的情况下更新 Firebase 数据库中的数据
- go - 在 Go 中处理混合类型的哈希的替代方案
- sql - 从查询结果创建新表
- kentico - 具有 URL“路径或模式”功能的 Kentico 自定义页面 URL
- python-3.x - 克服机器学习模型早期收敛的最佳方法