0

我有一个由字典列表组成的时间序列,如下所示:

for i in range(10):
    d = {
        'ts': i,
        'ts_offset': 6 * 60 * 60,
        'value': 1234.0
    }
    if i >= 5:
        d['ts_offset'] = 12 * 60 * 60
    data.append(d)
frame = pd.DataFrame(data)
frame.index = pd.to_datetime(frame.ts, unit='s')

                        ts  ts_offset   value
ts                                        
1970-01-01 00:00:00   0      21600  1234.0
1970-01-01 00:00:01   1      21600  1234.0
1970-01-01 00:00:02   2      21600  1234.0
1970-01-01 00:00:03   3      21600  1234.0
1970-01-01 00:00:04   4      21600  1234.0
1970-01-01 00:00:05   5      43200  1234.0
1970-01-01 00:00:06   6      43200  1234.0
1970-01-01 00:00:07   7      43200  1234.0
1970-01-01 00:00:08   8      43200  1234.0
1970-01-01 00:00:09   9      43200  1234.0

索引是时间戳加上依赖于本地化的偏移量(以秒为单位)。如您所见,我的用例是偏移量可能在时间序列中的任何时候发生变化。我想将此构造转换为索引为本地化 pd.TimeSeriesIndex 的系列,但到目前为止,我只能找到适用于整个索引的本地化函数。

有人知道用(可能)单独的时区转换每个索引的有效方法吗?该系列最多可以包含几千行,并且这个函数会被调用很多,所以我想尽可能地向量化。


编辑:

我冒昧地使用以下脚本对 FLabs 分组解决方案与简单的 python 循环进行计时:

import pandas as pd
import numpy as np
import datetime


def to_series1(data, metric):
    idx = []
    values = []
    for i in data:
        tz = datetime.timezone(datetime.timedelta(seconds=i["ts_offset"]))
        idx.append(pd.Timestamp(i["ts"] * 10**9, tzinfo=tz))
        values.append(np.float(i["value"]))
    series = pd.Series(values, index=idx, name=metric)
    return series


def to_series2(data, metric):
    frame = pd.DataFrame(data)
    frame.index = pd.to_datetime(frame.ts, unit='s', utc=True)
    grouped = frame.groupby('ts_offset')

    out = {}
    for name, group in grouped:
        out[name] = group
        tz = datetime.timezone(datetime.timedelta(seconds=name))
        out[name].index = out[name].index.tz_convert(tz)

    out = pd.concat(out, axis=0).sort_index(level='ts')
    out.index = out.index.get_level_values('ts')
    series = out.value
    series.name = metric
    series.index.name = None
    return series


metric = 'bla'
data = []
for i in range(100000):
    d = {
        'ts': i,
        'ts_offset': 6 * 60 * 60,
        'value': 1234.0
    }
    if i >= 50000:
        d['ts_offset'] = 12 * 60 * 60
    data.append(d)

%timeit to_series1(data, metric)

%timeit to_series2(data, metric)

结果如下:

2.59 s ± 113 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.03 s ± 125 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

所以我仍然愿意接受可能更快的建议。

4

1 回答 1

1

您可以使用groupby ts_offset,以便您可以将单个偏移量应用于数据帧(矢量化操作):

grouped = frame.groupby('ts_offset')

out = {}
for name, group in grouped:
    print(name)
    out[name] = group
    out[name].index = out[name].index + pd.DateOffset(seconds=name)

out = pd.concat(out, axis=0, names=['offset', 'ts']).sort_index(level='ts')

显示应用的偏移量只是为了验证结果,您有:

Out[17]: 
                           ts  ts_offset   value
      ts                                        
21600 1970-01-01 06:00:00   0      21600  1234.0
      1970-01-01 06:00:01   1      21600  1234.0
      1970-01-01 06:00:02   2      21600  1234.0
      1970-01-01 06:00:03   3      21600  1234.0
      1970-01-01 06:00:04   4      21600  1234.0
43200 1970-01-01 12:00:05   5      43200  1234.0
      1970-01-01 12:00:06   6      43200  1234.0
      1970-01-01 12:00:07   7      43200  1234.0
      1970-01-01 12:00:08   8      43200  1234.0
      1970-01-01 12:00:09   9      43200  1234.0

最后,您可以删除第一个索引:

out.index = out.index.get_level_values('ts')
于 2018-11-12T13:11:12.880 回答