首页 > 解决方案 > 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可以直接使用?或者我可以对上面的功能做出任何其他更好的方法或改进?

标签: dataframejulia

解决方案


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.


推荐阅读