繁体   English   中英

从 2 个一维数组生成二维数组的矢量化方法

[英]Vectorized way to generate 2D array from 2 1D arrays

我有一对等长的 numpy 数组。 dwells包含代表停留时间的浮点数,而ids代表一个状态。 在我的示例中,只有 3 个标记为012独特状态。

dwells = np.array([4.3,0.2,3,1.5])
ids = np.array([2, 0, 1, 2])

之前的 2 个数组模拟了一个系统,该系统从状态2开始,在那里停留4.3秒,跳转到状态0 ,停留0.2秒等等。 我想生成另一个 numpy 数组。 它需要与dwells.sum()一样多的列,每列代表一个整数0,1,2,3...表示时间。 每行都匹配唯一状态之一(在本例中为 3)。 该数组的每个元素代表该时间段内每个状态的相对贡献。 例如,在前 4 个时间点,只有状态 2 有任何贡献,因此第 2 行的第 4 个元素等于1 第五列有来自所有 3 个状态的贡献,但sum等于1

[[0, 0, 0, 0, 0.2, 0, 0,  0,  0]
 [0, 0, 0, 0, 0.5, 1, 1, 0.5, 0]
 [1, 1, 1, 1, 0.3, 0, 0, 0.5, 1]]

我可以用for循环来做到这一点,但我想知道是否有更有效的矢量化方式。

假设我们有一个最小的时间步长delta

import numpy as np

dwells = np.array([4.3,0.2,3,1.5])
ids = np.array([2, 0, 1, 2])

def dwell_map(dwells, ids, delta=0.1):
    import numpy as np
    import sys

    idelta = 1 / delta

    # ensure that idelta is an integer number
    if not idelta.is_integer():
        raise ValueError("1/delta is not integer") 

    idelta = int(idelta)

    # create new longer dwells array
    dwells_l = (dwells*idelta).astype(int)

    # create target array
    a = np.zeros((ids.max()+1, dwells_l.sum().astype(int)), dtype=int)

    # create repeats of the ids according to the dwell time
    ind = np.repeat(ids, dwells_l)

    # put ones at the position where we have the indices
    a[ind, np.arange(ind.size)] = 1

    # reduce back to the original time resolution
    a = a.reshape(ids.max()+1, -1, idelta).sum(axis=2)/idelta

    return a

res = dwell_map(dwells, ids, 0.1)

这只有在 delta 足够大并且总持续时间足够小时才能很好地工作,因此中间数组不会“无限”增长。

根据您的示例数组的 iPython %timeit魔术的性能,将其与您的 for 循环解决方案进行比较:

10000 loops, best of 5: 58.5 µs per loop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM