获取二维数组中每列的第二个最小值


15

如何从每一列中获取第二个最小值?我有这个数组:

A = [[72 76 44 62 81 31]
     [54 36 82 71 40 45]
     [63 59 84 36 34 51]
     [58 53 59 22 77 64]
     [35 77 60 76 57 44]]

我希望输出如下:

A = [54 53 59 36 40 44]

你有尝试过吗??
Meha Parekh

每列第二个最小值?
Nicolas Gervais

@NicolasGervais是的
Dan

Answers:


12

仅一行尝试一下:

[sorted(i)[1] for i in zip(*A)]

实际上:

In [12]: A = [[72, 76, 44, 62, 81, 31], 
    ...:      [54 ,36 ,82 ,71 ,40, 45], 
    ...:      [63 ,59, 84, 36, 34 ,51], 
    ...:      [58, 53, 59, 22, 77 ,64], 
    ...:      [35 ,77, 60, 76, 57, 44]] 

In [18]: [sorted(i)[1] for i in zip(*A)]                                                                                                                                                                           
Out[18]: [54, 53, 59, 36, 40, 44]

zip(*A) 将转置您的列表列表,使列变为行。

并且如果您有重复的值,例如:

In [19]: A = [[72, 76, 44, 62, 81, 31], 
    ...:  [54 ,36 ,82 ,71 ,40, 45], 
    ...:  [63 ,59, 84, 36, 34 ,51], 
    ...:  [35, 53, 59, 22, 77 ,64],   # 35
    ...:  [35 ,77, 50, 76, 57, 44],]  # 35

如果您需要同时跳过两个35,则可以使用set()

In [29]: [sorted(list(set(i)))[1] for i in zip(*A)]                                                                                                                                                                
Out[29]: [54, 53, 50, 36, 40, 44]

6

numpy数组上的操作应使用numpy函数来完成,因此请看以下内容:

np.sort(A, axis=0)[1, :]
Out[61]: array([54, 53, 59, 36, 40, 44])

据我所知,这必须是最好的解决方案,它将所有内容保留在其中numpy,我认为lambda必须放慢heapq.nsmallest解决方案。似乎最好将一切保持在快速状态numpy
jamylak

3

您可以使用heapq.nsmallest

from heapq import nsmallest

[nsmallest(2, e)[-1] for e in zip(*A)]

输出:

[54, 53, 50, 36, 40, 44]

我添加了一个简单的基准来比较已经发布的不同解决方案的性能:

在此处输入图片说明

from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest


b = BenchmarkBuilder()

@b.add_function()
def MehrdadPedramfar(A):
    return [sorted(i)[1] for i in zip(*A)]

@b.add_function()
def NicolasGervais(A):
    return np.sort(A, axis=0)[1, :]

@b.add_function()
def imcrazeegamerr(A):
    rotated = zip(*A[::-1])

    result = []
    for arr in rotated:
        # sort each 1d array from min to max
        arr = sorted(list(arr))
        # add the second minimum value to result array
        result.append(arr[1])

    return result

@b.add_function()
def Daweo(A):
    return np.apply_along_axis(lambda x:heapq.nsmallest(2,x)[-1], 0, A)

@b.add_function()       
def kederrac(A):
    return [nsmallest(2, e)[-1] for e in zip(*A)]


@b.add_arguments('Number of row/cols (A is  square matrix)')
def argument_provider():
    for exp in range(2, 18):
        size = 2**exp
        yield size, [[randint(0, 1000) for _ in range(size)] for _ in range(size)]

r = b.run()
r.plot()

zipsorted功能配合使用是2D小型列表的最快解决方案,而zipheapq.nsmallest节目配合使用则在2D大型列表上最好


1
只是一个疯狂的想法:您生成的不是numpy dtypes的数字会影响这些结果吗?另外,内置的randint不会返回列表而不是数组吗?
Nicolas Gervais

1

我希望我能正确理解您的问题,但是无论如何,这是我的解决方案,我确信这样做的方式更加优雅,但确实有效

A = [[72,76,44,62,81,31]
 ,[54,36,82,71,40,45]
 ,[63,59,84,36,34,51]
 ,[58,53,59,22,77,64]
 ,[35,77,50,76,57,44]]

#rotate the array 90deg
rotated = zip(*A[::-1])

result = []
for arr in rotated:
    # sort each 1d array from min to max
    arr = sorted(list(arr))
    # add the second minimum value to result array
    result.append(arr[1])
print(result)

在此处输入图片说明


0

假设A是这样numpy.array(如果这是真的,请考虑numpy在您的问题中添加标签),那么您可以使用apply_along_axis以下方式:

import heap
import numpy as np
A = np.array([[72, 76, 44, 62, 81, 31],
              [54, 36, 82, 71, 40, 45],
              [63, 59, 84, 36, 34, 51],
              [58, 53, 59, 22, 77, 64],
              [35, 77, 60, 76, 57, 44]])
second_mins = np.apply_along_axis(lambda x:heapq.nsmallest(2,x)[-1], 0, A)
print(second_mins)  # [54 53 59 36 40 44]

请注意,我使用了heapq.nsmallest,因为它会根据需要进行尽可能多的排序以获取2个最小的元素,sorted这与完成排序不同。


0
>>> A = np.arange(30).reshape(5,6).tolist()
>>> A
[[0, 1, 2, 3, 4, 5], 
 [6, 7, 8, 9, 10, 11], 
 [12, 13, 14, 15, 16, 17], 
 [18, 19, 20, 21, 22, 23],
 [24, 25, 26, 27, 28, 29]]

更新set用于防止使用重复和转置列表zip(*A)

>>> [sorted(set(items))[1] for items in zip(*A)]
[6, 7, 8, 9, 10, 11]

旧:每行第二个最小项

>>> [sorted(set(items))[1] for items in A]
[1, 7, 13, 19, 25]

这不是在每一行而不是每一列中获得第二项吗?
paxdiablo

@paxdiablo是的,谢谢您的通知。更新的答案。
Dishin H Goyani
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.