如何在包装后的DataFrame上获取@view?

huangapple go评论74阅读模式
英文:

How to get a @view on a wrapped DataFrame?

问题

我已经封装了一个类似这样的DataFrame,以便编写一些辅助方法。我想要在这个向量上创建一个视图:

series = MySeries{Float64}()
datetimes = @view series[:, :datetime]

function MySeries{T}() where {T}
  data = DataFrame(
    datetime=DateTime[],
    data=T[])
  MySeries{T}(data)
end

@inline Base.push!(S::MySeries, dt::DateTime, data) = push!(S.data, [dt, data])
@inline Base.getindex(S::MySeries, i, j) = S.data[i, j]
@inline Base.setindex!(S::MySeries, value, i, j) = S.data[i, j] = value

如果需要进一步的解释或帮助,请随时提问。

英文:

I have wrapped a DataFrame like this in order to write some helper methods. I want to get a view on the vector:

series = MySeries{FLoat64}()
datetimes = @view series[:, :datetime]

function MySeries{T}() where {T}
  data = DataFrame(
    datetime=DateTime[],
    data=T[])
  MySeries{T}(data)
end

@inline Base.push!(S::MySeries, dt::DateTime, data) = push!(S.data, [dt, data])
@inline Base.getindex(S::MySeries, i, j) = S.data[i, j]
@inline Base.setindex!(S::MySeries, value, i, j) = S.data[i, j] = value

答案1

得分: 1

这应该可以工作:

Base.view(S::MySeries{T}, i, j) where T = MySeries{T}(Base.view(S.data, i, j))


此外,您可能需要:

Base.getindex(S::MySeries{T}, i, j) where T = MySeries{T}(S.data[i, j])


因为目前您的 `getindex` 函数会解包对象。

最后,您可能希望更仔细地检查 `i` 和 `j` 索引(如果它们是标量选择器,一个维度将被删除,我不确定您的 `MySeries` 对象需要/假设什么)。
英文:

This should work:

Base.view(S::MySeries{T}, i, j) where T = MySeries{T}(Base.view(S.data, i, j))

Also you probably want:

Base.getindex(S::MySeries{T}, i, j) where T = MySeries{T}(S.data[i, j])

as currently your getindex unwraps the object.

Finally you might want to make a more careful checks of i and j indices (as if they are scalar selectors a dimension is dropped and I am not sure what your MySeries object requires/assumes).

huangapple
  • 本文由 发表于 2023年8月5日 07:53:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定