【问题标题】:How to repeat same datetime data for different interval如何为不同的时间间隔重复相同的日期时间数据
【发布时间】:2021-10-23 11:38:07
【问题描述】:

我有这个数据集

                     Value1      Value2
2000-01-01 12:00:00     1        2

2000-01-02 12:00:00     3        4  
2000-01-03 12:00:00     5        6

例如,我想以 4 个不同的时间间隔重复相同的数据

                     Value1      Value2
2000-01-01 00:00:00   1            2

2000-01-01 06:00:00   1            2    
2000-01-01 12:00:00   1            2    
2000-01-01 18:00:00   1            2    

2000-01-02 00:00:00      3          4

2000-01-02 06:00:00      3          4

2000-01-02 12:00:00      3          4


2000-01-02 18:00:00      3          4

 

等等。

【问题讨论】:

  • df.resample('6H').ffill() 您可以在 6 小时内重新采样数据,然后对空值进行前向填充

标签: python python-3.x pandas time-series


【解决方案1】:
  • 您的日期是连续的,此解决方案也适用于不连续的日期
  • 生成一个作为扩展时间的系列,然后外连接
import pandas as pd
import io

df = pd.read_csv(io.StringIO("""                     Value1      Value2
2000-01-01 12:00:00     1        2
2000-01-02 12:00:00     3        4  
2000-01-03 12:00:00     5        6"""), sep="\s\s+", engine="python")

df = df.set_index(pd.to_datetime(df.index))

df = df.join(
    pd.Series(df.index, index=df.index)
    .rename("expanded")
    .dt.date.apply(lambda d: pd.date_range(d, freq="6H", periods=4))
    .explode()
).set_index("expanded")

df

expanded Value1 Value2
2000-01-01 00:00:00 1 2
2000-01-01 06:00:00 1 2
2000-01-01 12:00:00 1 2
2000-01-01 18:00:00 1 2
2000-01-02 00:00:00 3 4
2000-01-02 06:00:00 3 4
2000-01-02 12:00:00 3 4
2000-01-02 18:00:00 3 4
2000-01-03 00:00:00 5 6
2000-01-03 06:00:00 5 6
2000-01-03 12:00:00 5 6
2000-01-03 18:00:00 5 6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    相关资源
    最近更新 更多