如何从列表中的每个numpy数组中提取最大值?

时间:2019-04-15 05:33:11

标签: python numpy

实际上,我是python的新手,正在研究一些图像问题声明。陷入问题,无法摆脱困境。

我的数据框如下:

Image                       RGB                 max_1 max_2 max_3
file1   [[224,43,234][22,5,224][234,254,220]]     234   224   254
file2   [[22,143,113][221,124,224][234,254,123]]  143   224   254
file3   [[44,45,2][2,5,4][34,254,220]]             45     5   254
file4   [[224,243,34][22,5,24][24,25,20]]         243    24    25
file5   [[210,13,34][22,5,224][234,254,220]]      210   224   254

我尝试了np.max(),但是它给了我意外的结果,这意味着对于第一行,它给了我输出254,依此类推。

我期望输出为max_1,max_2和max_3列。

6 个答案:

答案 0 :(得分:2)

我假设您分别需要R,G和B的最大值。 如果您要这样做,这是一种方法:

a = np.array([ [224,43,234], [22,5,224], [234,254,220]])
r_max = a.T[0].max()
g_max = a.T[1].max()
b_max = a.T[2].max()

答案 1 :(得分:2)

使用list-comprehension

a = np.array([[224,43,234], [22,5,224], [234,254,220]])

print([x.max() for x in a])

输出

[234, 224, 254]

答案 2 :(得分:1)

您也许可以执行以下操作:

file1 = [[224,43,234],[22,5,224],[234,254,220]]

for idx, inner_list in enumerate(file1):
    print('max_'+str(idx+1)+' : '+str(max(inner_list)))

答案 3 :(得分:1)

另一种方式:

import numpy as np

a=np.array([[1,2,3],[11,12,13],[21,22,23]])
print(a)

maxInRows = np.amax(a, axis=1)
print('Max value of every Row: ', maxInRows)

答案 4 :(得分:0)

您说您有一个数据框,所以我认为它是一个pandas DataFrame对象。 在这种情况下,您可以使用列表推导从列表中的每个子列表中获取最大值,然后将每个元素分配给新的列(此循环并不完美,但可以使用):

df['max_colors'] = df['RGB'].apply(lambda x: [np.max(color) for color in x])
for i in range(3):
    df['max_'+str(i)] = df['max_colors'].apply(lambda x: x[i])

答案 5 :(得分:0)

解决了这样的问题。感谢您提供所有答案。

df['max_1'] = 0
df['max_2'] = 0
df['max_3'] = 0
for i in range(5):
    df['max_1'][i] = df['RGB'][i][0].max()
    df['max_2'][i] = df['RGB'][i][1].max()
    df['max_3'][i] = df['RGB'][i][2].max()