代码之家  ›  专栏  ›  技术社区  ›  Venugopal Bukkala

对于文件中的每一行,查找时间戳差异至少为n秒的下一行

  •  1
  • Venugopal Bukkala  · 技术社区  · 7 年前

    我是Python时间序列编程新手。以下是示例文件:

    DateTime<space> Price <space> Data1<space> Data2
    
    Sample file contents:
    20171105 09:20:01.134 2123.00 12.23 34.12
    20171105 09:20:01.789 2133.00 32.43 45.62
    20171105 09:20:02.238 2423.00 35.43 55.62
    20171105 09:20:02.567 3423.00 65.43 56.62
    20171105 09:20:02.948 2463.00 45.43 58.62
    
    Date Format:
    YYYYMMDD hh:mm:ss.mi
    YYYY => Year
    MM => Month starting from 01
    DD => Day of month starting from 01
    hh => hour
    mm => minute
    ss => second
    mi => milliseconds
    

    假设我们必须将价格移动n秒。对于中的每一行 在文件中,找到时间戳差异至少为n秒的下一行。假设我们在l1行,下一行时间戳差为n秒的是l2。那么l1的转移时间就是l2的价格——l1的价格。 让我们计算出上述逻辑。假设换档时间间隔为1秒。然后 相隔1秒的线条为:

    成对(第一行,第三行),(第二行,第五行)。第三、第四和第五行没有一对,即没有时间戳差大于或等于1秒的行。

    一线移动价格为2423.00-2123.00=300 二线价格变动为2463.00-2133.0=330 3号、4号和5号线没有变动价格。

    有人能帮我在Pandad中编写代码吗。。非常感谢。

    1 回复  |  直到 7 年前
        1
  •  0
  •   jakevdp    7 年前

    以下是一种方法:

    import pandas as pd
    
    # read CSV and parse dates
    df = pd.read_csv('tmp.csv', delim_whitespace=True, names=range(5),
                     parse_dates={'date': [0, 1]})
    
    # find indices of shifted values
    n = 1
    shifted = df['date'] + pd.Timedelta(n, 's')
    indices = df['date'].searchsorted(shifted)
    
    # add a column with the shift
    df['shift'] = df[2].reindex(indices).reset_index(drop=True) - df[2]
    print(df)
    

    结果是:

                         date       2      3      4  shift
    0 2017-11-05 09:20:01.134  2123.0  12.23  34.12  300.0
    1 2017-11-05 09:20:01.789  2133.0  32.43  45.62  330.0
    2 2017-11-05 09:20:02.238  2423.0  35.43  55.62    NaN
    3 2017-11-05 09:20:02.567  3423.0  65.43  56.62    NaN
    4 2017-11-05 09:20:02.948  2463.0  45.43  58.62    NaN