如何获得数组中数组的最小值和最大值?

2024-04-19 17:00:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到一列的最小值和最大值。你知道吗

这是我的测试代码:

from numpy import array
import numpy as np

test = [array([[619, 502, 551],
       [623, 502, 551],
       [624, 504, 551]]),
 array([[624, 498, 531],
       [628, 502, 529]]),
 array([[619, 496, 557],
       [892, 508, 559]]),
 array([[619, 494, 561],
       [895, 506, 559],
       [902, 512, 559]]),
 array([[619, 494, 559],
       [918, 510, 567]]),
 array([[619, 493, 561],
       [931, 512, 561],
       [932, 512, 561]]),
 array([[619, 494, 561],
       [942, 510, 559]]),
 array([[619, 493, 561],
       [620, 493, 559],
       [948, 512, 561]]),
 array([[619, 494, 591],
       [752, 542, 633]]),
 array([[626, 465, 567],
       [766, 532, 633]])]

data = array(test)

我尝试了np.min,不同的索引,但没有成功。你知道吗

我希望得到列2(或任何列)的最小值和最大值

我不能使用for循环遍历每一项,因为实际数据中有很多这样的循环。你知道吗

如有任何建议,我们将不胜感激。谢谢您。你知道吗


Tags: 数据fromtestimportnumpyfordataas
3条回答

IIUC,你可以做stack

np.vstack([d for d in data]).min(axis=0)

输出:

array([619, 465, 529])

如果列相同,可以尝试以下操作来获取最小/最大值。你知道吗

In [28]: test = [[[619, 502, 551],
    ...:        [624, 504, 551]],
    ...: [[624, 498, 531],
    ...:        [628, 502, 529]],
    ...: [[619, 496, 557],
    ...:        [892, 508, 559]],
    ...: [[619, 494, 561],
    ...:        [895, 506, 559],
    ...:        [902, 512, 559]],
    ...: [[619, 494, 559],
    ...:        [918, 510, 567]],
    ...: [[619, 493, 561],
    ...:        [931, 512, 561],
    ...:        [932, 512, 561]],
    ...: [[619, 494, 561],
    ...:        [942, 510, 559]],
    ...: [[619, 493, 561],
    ...:        [620, 493, 559],
    ...:        [948, 512, 561]],
    ...: [[619, 494, 591],
    ...:        [752, 542, 633]],
    ...: [[626, 465, 567],
    ...:        [766, 532, 633]]]

In [29]: test1 = []

In [30]: [test1.append(t) for t1 in test for t in t1]

In [31]: test1
Out[31]:
[[619, 502, 551],
 [624, 504, 551],
 [624, 498, 531],
 [628, 502, 529],
 [619, 496, 557],
 [892, 508, 559],
 [619, 494, 561],
 [895, 506, 559],
 [902, 512, 559],
 [619, 494, 559],
 [918, 510, 567],
 [619, 493, 561],
 [931, 512, 561],
 [932, 512, 561],
 [619, 494, 561],
 [942, 510, 559],
 [619, 493, 561],
 [620, 493, 559],
 [948, 512, 561],
 [619, 494, 591],
 [752, 542, 633],
 [626, 465, 567],
 [766, 532, 633]]

In [32]: np.amin(test1, None)
Out[32]: 465

In [33]: np.max(test1, None)
Out[33]: 948

如果您只寻找一列,那么可以使用numpy数组的索引。 e、 g

arr = np.asarray(((1,2,3),(4,5,6),(7,8,9)))
print(arr)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

通过切片,可以将列作为子阵列,如下例所示

print(arr[:,0])
[1 4 7]

相关问题 更多 >