gpt4 book ai didi

python - 我如何在 Python 中生成条件矩阵?

转载 作者:行者123 更新时间:2023-11-28 22:09:54 25 4
gpt4 key购买 nike

我正在做一个模拟,我想建立一个 numpy 矩阵来表示模拟的状态。

比如我通过模拟得到了一个矩阵A=

matrix( [[0.        , 0.024     , 0.088     , 0.154     , 0.206      ],
[0. , 0.3300 , 0.654 , 1 , 0.5 ],
[0. , 0.1770 , 0.371 , 0.5149487 , 0.610 ],
[0. , 0. , 0.5 , 0.8 , 0.9 ],
[0. , 0. , 1 , 0.9 , 0.8 ]])

If A[i,j]>=1:
B[i,j]=1
else:
B[i,j]=0

If in one row, one element >=1, the following elements in that row all equal to 1.如果我想在不使用 for 循环的情况下实现这一点,我该怎么办?

我要得到的B是:

matrix([[0, 0, 0, 0, 0],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 1, 1, 1]])

最佳答案

我们可以使用np.maximum.accumulate在与 1 比较之后。

输入:

In [79]: a
Out[79]:
matrix([[0. , 0.024 , 0.088 , 0.154 , 0.206 ],
[0. , 0.33 , 0.654 , 1. , 0.5 ],
[0. , 0.177 , 0.371 , 0.5149487, 0.61 ],
[0. , 0. , 0.5 , 0.8 , 0.9 ],
[0. , 0. , 1. , 0.9 , 0.8 ]])

导致解决方案的步骤:

# Compare against 1
In [93]: a>=1
Out[93]:
matrix([[False, False, False, False, False],
[False, False, False, True, False],
[False, False, False, False, False],
[False, False, False, False, False],
[False, False, True, False, False]])

# Get accumulated max along each row. Thus, it makes sure that once we
# encounter a match(True), it's maintained till the end.
In [91]: np.maximum.accumulate(a>=1,axis=1)
Out[91]:
matrix([[False, False, False, False, False],
[False, False, False, True, True],
[False, False, False, False, False],
[False, False, False, False, False],
[False, False, True, True, True]])

# View as int8/uint8 dtype. It's meant for memory efficiency to have
# the final output as int dtype
In [92]: np.maximum.accumulate(a>=1,axis=1).view('i1')
Out[92]:
matrix([[0, 0, 0, 0, 0],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 1, 1]], dtype=int8)

大型数据集(给定样本沿行和列重复10000x)在所有提议的解决方案上的时间(因为我们似乎关心性能)-

# Repeated along rows
In [106]: ar = np.repeat(a,10000,axis=0)

In [108]: %timeit (ar >= 1.).cumsum(axis=1, dtype=bool).view('i1')
...: %timeit np.maximum.accumulate(ar>=1,axis=1).view('i1')
582 µs ± 1.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
593 µs ± 15 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# Repeated along rows and cols
In [109]: ar = np.repeat(np.repeat(a,1000,axis=0),1000,axis=1)

In [110]: %timeit (ar >= 1.).cumsum(axis=1, dtype=bool).view('i1')
...: %timeit np.maximum.accumulate(ar>=1,axis=1).view('i1')
77.9 ms ± 1.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
77.3 ms ± 628 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

关于python - 我如何在 Python 中生成条件矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57114874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com