python - 从 2 个 1D 数组生成 2D 数组的矢量化方法

标签 python arrays numpy vectorization

我有一对等长的 numpy 数组。 dwells包含代表停留时间的 float ,并且 ids代表一种状态。在我的示例中,只有 3 个标记为 0 的独特状态。 , 1 , 2 .

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)

只有当增量足够大并且总持续时间足够小时,这才有效,这样中间数组就不会“无限”变大。

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

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

关于python - 从 2 个 1D 数组生成 2D 数组的矢量化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59037789/

相关文章:

python - 将 Curl "-I --user"转换为 Python 请求

javascript - 添加到数组 javascript

c - 为什么不建议在 C 中使用指针进行数组访问

Python、cPickle、 pickle lambda 函数

python - 从无形状向量生成零矩阵

python - 从只有一个参数集的旧函数生成新函数

python - 如何根据 Pandas 中的一列列表组合两个数据框

c# - 如何添加方法来操作类对象数组?

python - 更好的方法来统一打乱两个 numpy 数组

Python在没有-inf的情况下获取最小值