首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在朱莉娅中的总和,如R或熊猫

在朱莉娅中的总和,如R或熊猫
EN

Stack Overflow用户
提问于 2018-06-11 12:33:45
回答 1查看 891关注 0票数 1

我想按季度频率汇总一个月序列,其中Rtsaggregate() (参见the first answer on this thread),pandasdf.resample("Q").sum() (参见this question)。朱莉娅也提供类似的东西吗?

附录:我目前的解决方案使用一个函数将数据转换为第一季度和拆分应用-合并:

代码语言:javascript
复制
"""
    month_to_quarter(date)

Returns the date corresponding to the first day of the quarter enclosing date

# Examples
```jldoctest

julia> Date(1990,1,1) == RED.month_to_quarter(日期(1990,2,1))

真的

julia> Date(1990,1,1) == RED.month_to_quarter(日期(1990,1,1))

真的

julia> Date(1990,1,1) == RED.month_to_quarter(日期(1990,2,25))

真的

代码语言:javascript
复制
"""
function month_to_quarter(date::Date)
    new_month = 1 + 3 * floor((Dates.month(date) - 1) / 3)
    return Date(Dates.year(date), new_month, 1)
end


""" 
    monthly_to_quarterly(monthly_df)

Aggregates a monthly data frame to the quarterly frequency. The data frame should have a :DATE column.

# Examples
```jldoctest

julia>月=转换(DataFrame,hcat(Dates.Date(1990,m,1) in 1:3),1;2;3);

julia>重命名!(每月,:x1 => :DATE);

julia>重命名!(每月,:x2 => :value);

julia>季刊=RED.monthly_to_quarterly(月);

julia>季刊:价值

2.0

julia>长度(季度:值)

1

代码语言:javascript
复制
"""
function monthly_to_quarterly(monthly::DataFrame)

    # quarter months: 1, 4, 7, 10
    quarter_months = collect(1:3:10)

    # Deep copy the data frame
    monthly_copy = deepcopy(monthly)

    # Drop initial rows until it starts on a quarter
    while !in(Dates.month(monthly_copy[:DATE][1]), quarter_months)

        # Verify that something is left to pop
        @assert 1 <= length(monthly_copy[:DATE])

        monthly_copy = monthly_copy[2:end, :]
    end

    # Drop end rows until it finishes before a quarter
    while !in(Dates.month(monthly_copy[:DATE][end]), 2 + quarter_months)
    monthly_copy = monthly_copy[1:end-1, :]
    end

    # Change month of each date to the nearest quarter
    monthly_copy[:DATE] = month_to_quarter.(monthly_copy[:DATE])

    # Split-apply-combine
    quarterly = by(monthly_copy, :DATE, df -> mean(df[:value]))

    # Rename
    rename!(quarterly, :x1 => :value)

    return quarterly

end
EN

回答 1

Stack Overflow用户

发布于 2018-06-12 14:12:11

我在文档里找不到这样的功能。下面是您自己的答案的更多DataFrames.jl版本和更简洁的版本

代码语言:javascript
复制
using DataFrames
# copy-pasted your own function
function month_to_quarter(date::Date)
    new_month = 1 + 3 * floor((Dates.month(date) - 1) / 3)
    return Date(Dates.year(date), new_month, 1)
end

# the data
r=collect(1:6)
monthly = DataFrame(date=[Dates.Date(1990, m, 1) for m in r], 
            val=r);

# the functionality
monthly[:quarters] = month_to_quarter.(monthly[:date])
_aggregated = by(monthly, :quarters, df -> DataFrame(S = sum(df[:val])))

@show monthly
@show _aggregated
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50797858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档