【问题标题】:Is there a way to convert a column to a timeseries object of 30 minute interval?有没有办法将列转换为 30 分钟间隔的时间序列对象?
【发布时间】:2021-05-18 16:43:41
【问题描述】:

我有一个数据框df,其中包含三列groupphasecount

首先,我想将 phase 列转换为 30 分钟间隔的时间序列对象。例如,阶段 0 -> 0 分钟,阶段 2 -> 30 分钟,阶段 3 -> 60 分钟......

其次,我想为每个组(A、B 和 C)绘制时间序列(计数与相位) - 可能使用 for 循环来绘制所有三个数字

最终目标:比较 A 组、B 组和 C 组的时间序列

#df
group,phase, count 
A,0,3000
A,1,3315
A,2,3690
A,3,4002
A,4,4210
B,0, 2000
B,1,2100
B,2,2215
B,3,2303
B,4,2412
C,0,3001
C,1,3120
C,2,3225
C,3,3350
C,4,3459


期望的输出

# in a time series format 
group,phase, count
A, 0, 3000
A, 30, 3315
A, 60, 3690
A, 90, 4002
A, 120, 4210
B, 0, 2000
B, 30, 2100
B, 60, 2215
B, 90, 2303
B, 120, 2412
C, 0, 3001
C, 30, 3120
C, 60, 3225
C, 90, 3350
C, 120, 3459

谢谢

【问题讨论】:

    标签: python r for-loop time-series


    【解决方案1】:

    我们可以为此使用R 索引。将 1 添加到“相位”(R 索引从 1 开始),然后按替换顺序传递值向量

    library(dplyr)
    df1 %>%
        mutate(phase = c(0, 30, 60, 90, 120)[phase + 1])
    

    -输出

    #    group phase count
    #1      A     0  3000
    #2      A    30  3315
    #3      A    60  3690
    #4      A    90  4002
    #5      A   120  4210
    #6      B     0  2000
    #7      B    30  2100
    #8      B    60  2215
    #9      B    90  2303
    #10     B   120  2412
    #11     C     0  3001
    #12     C    30  3120
    #13     C    60  3225
    #14     C    90  3350
    #15     C   120  3459
    

    或者另一个选项是seq

    df1 %>%
        group_by(group) %>%
        mutate(phase = seq(0, length.out = n(), by = 30))
    

    base R

    df1$phase <- c(0, 30, 60, 90, 120)[df1$phase + 1]
    

    数据

    df1 <- structure(list(group = c("A", "A", "A", "A", "A", "B", "B", "B", 
    "B", "B", "C", "C", "C", "C", "C"), phase = c(0L, 1L, 2L, 3L, 
    4L, 0L, 1L, 2L, 3L, 4L, 0L, 1L, 2L, 3L, 4L), count = c(3000L, 
    3315L, 3690L, 4002L, 4210L, 2000L, 2100L, 2215L, 2303L, 2412L, 
    3001L, 3120L, 3225L, 3350L, 3459L)), class = "data.frame", row.names = c(NA, 
    -15L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-12
      • 2021-02-21
      • 2013-12-26
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多