如何在Python中找到二维数组中每一列的最小元素

时间:2020-06-02 07:43:17

标签: python python-3.x list

import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')

我需要在二维数组中找到每一列的最小元素,并将它们添加到新数组(一维数组)中

4 个答案:

答案 0 :(得分:0)

使用np.min(arr_name, axis=1)

答案 1 :(得分:0)

只需在每列和列表理解中使用min。

x_new = [min(x_i) for x_i in x]

答案 2 :(得分:0)

您可以使用列表推导将min应用于数据的每一列:

import random
x =[[random.randint(1,10) for j in range(5)] for i in range(4)]
for i in range(4):
    for j in range(5):
        print("%4d" % (x[i][j]), end="")
    print(end='\n')

print([min(x[i][j] for i in range(4)) for j in range(5)])

样本输出:

   8   1   7   6   9
   9   2   8   6   8
  10   5   3   3   5
   1   9   7  10   9

[1, 1, 3, 3, 5]

答案 3 :(得分:0)

您应该查看numpy(),尤其是np.min()。该代码可以是:

# Convert 'x' to np array-
x_np = np.asarray(x)

# Sanity check-
x_np
'''
array([[ 8,  7, 10,  8,  8],
       [ 6,  6,  3,  6,  6],
       [ 9,  4,  2,  8,  3],
       [ 2,  4,  5,  3,  4]])
'''

# Minimum elements by squashing the columns-
np.min(x_np, axis = 1)
# array([7, 3, 2, 2])

# Minimum elements by squashing the rows-
np.min(x_np, axis = 0)
# array([2, 4, 2, 3, 3])