gpt4 book ai didi

python - NumPy - 使用权重对 2D 数组列进行向量化 bincount

转载 作者:太空宇宙 更新时间:2023-11-03 19:47:20 24 4
gpt4 key购买 nike

我一直在寻找解决方案herehere但不知道如何将其应用到我的结构中。

我有 3 个数组:一个由零组成的 (M, N) 和一个由索引组成的 (P,)(有些重复)和一个 (P, N) 值。

我可以用循环来完成它:

# a: (M, N)
# b: (P, N)
# ix: (M,)
for i in range(N):
a[:, i] += np.bincount(ix, weights=b[:, i], minlength=M)

我还没有看到任何以这种方式使用索引或使用 weights 关键字的示例。我知道我需要将所有内容放入一维数组中以对其进行矢量化,但是我正在努力弄清楚如何实现这一点。

最佳答案

基本思想与这些链接帖子中详细讨论的相同,即创建一个 2D bin 数组,其中每个要处理的“1D 数据”都有偏移量(在本例中为每个列)。因此,考虑到这些,我们最终会得到这样的结果 -

# Extent of bins per col
n = ix.max()+1

# 2D bins for per col processing
ix2D = ix[:,None] + n*np.arange(b.shape[1])

# Finally use bincount with those 2D bins as flattened and with
# flattened b as weights. Reshaping is needed to add back into "a".
a[:n] += np.bincount(ix2D.ravel(), weights=b.ravel(), minlength=n*N).reshape(N,-1).T

关于python - NumPy - 使用权重对 2D 数组列进行向量化 bincount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60046003/

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