python - NumPy:获取 3D 数组行和的 argmax 的最快方法

标签 python numpy multidimensional-array

假设我有一个 3 维数组,尺寸为 10x10000x5。将此数组解释为 10 个“子数组”,每个子数组有 10000 行和 5 列,我想要做的是,对于每一行:

(1) 计算 10 个子数组中每个子数组中行的总和。

(2) 确定哪个子数组的总和最高。

下面显示了一个示例。我执行上述操作,但仅针对前两行,其中“firstrow”是每个子数组的第一行的总和,“secondrow”是每个子数组的第二行的总和。然后,我使用 np.argmax() 查找产生最高总和的子数组。但我想对所有 10000 行执行此操作,而不仅仅是前两行。

import numpy as np
np.random.seed(777)
A = np.random.randn(10,10000,5)

first = [None]*10
second = [None]*10
for i in range(10):
    firstrow[i] = A[i].sum(axis=1)[0]
    secondrow[i] = A[i].sum(axis=1)[1]

np.argmax(np.array(firstrow)) # Sub-array 9 yields the highest sum
np.argmax(np.array(secondrow)) # Sub-array 8 yields the highest sum
#...

对于所有 10000 行,最快的方法是什么?

最佳答案

你可以这样做:

result = A.sum(2).argmax(0)

在您的示例中进行测试:

import numpy as np

np.random.seed(777)
A = np.random.randn(10, 10000, 5)

result = A.sum(2).argmax(0)

# Check against loop
first = [None] * 10
second = [None] * 10
for i in range(10):
    first[i] = A[i].sum(axis=1)[0]
    second[i] = A[i].sum(axis=1)[1]

print(result[0], np.argmax(np.array(first)))
# 9 9
print(result[1], np.argmax(np.array(second)))
# 8 8

关于python - NumPy:获取 3D 数组行和的 argmax 的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56777049/

相关文章:

c - 如何在 C 中声明一个非常大的 3 维数组?

python - 尝试从运行在 Linux 上的 django 查询 SQL Server - 无法打开 lib '/path/to/libtdsodbc.so'

python - Pandas groupby 累积/滚动总和、平均值和标准差

javascript - 处理时间长可能是由于 getValue 和单元格插入

python - NumPy 数组元素的自定义排列

python - 属性错误 : type object 'numpy.ndarray' has no attribute '__array_function__'

php - 来自二维 php 的分层二维 php 数组

python - 在交互式 python 调试 session 期间跳过指令

python - 为什么 os.mkdir() 在显式调用时变慢?

python - 如何使用 bisect 在需要时计算数组中进行搜索