LinearInterpolation不适用于DataFrames.jl中的变换



我定义了以下线性插值器:

julia> using DataFrames, Interpolations
julia> xs = 1:0.2:5;
julia> ys = log.(xs);
julia> li = LinearInterpolation(xs, ys);

并有一个数据帧:

julia> df = DataFrame(x=2:0.1:3)
11×1 DataFrame
Row │ x
│ Float64
─────┼─────────
1 │     2.0
2 │     2.1
3 │     2.2
4 │     2.3
5 │     2.4
6 │     2.5
7 │     2.6
8 │     2.7
9 │     2.8
10 │     2.9
11 │     3.0

我可以将数据帧的:x列传递给li,如下所示:

julia> li(df.x)
11-element Vector{Float64}:
0.6931471805599453
0.7408022704621078
0.7884573603642704
0.831963048859085
0.8754687373538997
0.915490091190668
0.9555114450274363
0.9925654311042973
1.0296194171811581
1.0641158529246337
1.0986122886681098

然而,当我尝试使用transform函数时,它失败了:

julia> transform(df, :x => li => :y)
ERROR: ArgumentError: Unrecognized column selector: :x => (21-element extrapolate(scale(interpolate(::Vector{Float64}, BSpline(Linear())), (1.0:0.2:5.0,)), Throw()) with element type Float64:

并抛出了一个我不理解的奇怪错误。如何解决这个问题?

您遇到的问题是LinearInterpolations.jsl没有将li定义为具有Function:的子类型

julia> li isa Function
false

li这样的对象在Julia中被称为函子,有时它们的作者不会选择将它们作为Function的子类型。在这种情况下,最简单的解决方案是使用匿名函数作为变通方法:

julia> transform(df, :x => (x -> li(x)) => :y)
11×2 DataFrame
Row │ x        y
│ Float64  Float64
─────┼───────────────────
1 │     2.0  0.693147
2 │     2.1  0.740802
3 │     2.2  0.788457
4 │     2.3  0.831963
5 │     2.4  0.875469
6 │     2.5  0.91549
7 │     2.6  0.955511
8 │     2.7  0.992565
9 │     2.8  1.02962
10 │     2.9  1.06412
11 │     3.0  1.09861

最新更新