python - numpy.amax 中的一个键

标签 python numpy max

在 Python 的标准中 max函数我可以传入一个key参数:

s = numpy.array(['one','two','three'])
max(s) # 'two' (lexicographically last)
max(s, key=len) # 'three' (longest string)

对于更大的(多维)数组,我们不能再使用max,但我们可以使用numpy.amax。 ...不幸的是不提供key参数

t = numpy.array([['one','two','three'],
                 ['four','five','six']], 
                dtype='object')
numpy.amax(t) # 'two` (max of the flat array)
numpy.amax(t, axis=1) # array([two, six], dtype=object) (max of first row, followed by max of second row)

我希望能够做的是:

amax2(t, key=len) # 'three'
amax2(t, key=len, axis=1) # array([three, four], dtype=object)

是否有内置方法来执行此操作?

注意:第一次尝试写这个问题时,我无法得到 amax working in this toy example !

最佳答案

这是一种非内置的方式(它在使用key时缺少features of amaxoutkeepdim参数),它看起来很长:

def amax2(x, *args, **kwargs):
    if 'key' not in kwargs:
        return numpy.amax(x,*args,**kwargs)
    else:
        key = kwargs.pop('key') # e.g. len, pop so no TypeError: unexpected keyword
        x_key = numpy.vectorize(key)(x) # apply key to x element-wise
        axis = kwargs.get('axis') # either None or axis is set in kwargs
        if len(args)>=2: # axis is set in args
            axis = args[1]

        # The following is kept verbose, but could be made more efficient/shorter    
        if axis is None: # max of flattened
            max_flat_index = numpy.argmax(x_key, axis=axis)
            max_tuple_index = numpy.unravel_index(max_flat_index, x.shape)
            return x[max_tuple_index]
        elif axis == 0: # max in each column
            max_indices = numpy.argmax(x_key, axis=axis)
            return numpy.array(
                 [ x[max_i, i] # reorder for col
                     for i, max_i in enumerate(max_indices) ], 
                 dtype=x.dtype)
        elif axis == 1: # max in each row
            max_indices = numpy.argmax(x_key, axis=axis)
            return numpy.array(
                 [ x[i, max_i]
                     for i, max_i in enumerate(max_indices) ],
                 dtype=x.dtype)

此功能的想法是从 @PeterSobot's answer 的第二部分扩展而来的到我之前的问题。

关于python - numpy.amax 中的一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12655525/

相关文章:

Python - 从 3D 数组写入三维图像

python - 减少 py2exe 分布大小,同时包含一些 numpy 函数

c++ - 在 OpenCV 中查找 SparseMat 的最大和最小位置

Python3 通过多处理并行化作业

python - 这是以编程方式终止(取消) celery 任务的最佳方式

python - 使用 Django 模型创建子类别

java - 尝试获取 2 个 arrayList 并将它们相乘并将新值存储到新的 arrayList 中以查找最小值/最大值

python - 从 Python 访问 VoltDB

python - Pymc3 中的随机索引

java - 为什么符号位不影响 Integer.MAX_VALUE 但影响 MIN 值?