python - 在最小值之前的每列值中找到最大值

标签 python pandas numpy

考虑数组a

a = np.array([
        [5, 4],
        [4, 5],
        [2, 2],
        [6, 1],
        [3, 7]
    ])

我可以找到最小值在哪里

a.argmin(0)

array([2, 3])

如何找到索引 2 之前的第 0 列值的最大值。对于第 1 列和索引 3 也是如此。更重要的是,它们在哪里?

如果我这样做

a.max(0)

array([6, 7])

但我需要

# max values
array([5, 5])

# argmax before mins
array([0, 1])

最佳答案

这是使用 broadcasting 的一种方法-

b = np.where(a.argmin(0) >= np.arange(a.shape[0])[:,None],a,np.nan)
idx = np.nanargmax(b,axis=0)
out = a[idx,np.arange(a.shape[1])]

sample 运行-

In [38]: a
Out[38]: 
array([[5, 4],
       [4, 5],
       [2, 2],
       [6, 1],
       [3, 7]])

In [39]: b = np.where(a.argmin(0) >= np.arange(a.shape[0])[:,None],a,np.nan)
    ...: idx = np.nanargmax(b,axis=0)
    ...: out = a[idx,np.arange(a.shape[1])]
    ...: 

In [40]: idx
Out[40]: array([0, 1])

In [41]: out
Out[41]: array([5, 5])

或者,如果 a 只有正数,我们可以简单地使用 -

得到 idx
mask = a.argmin(0) >= np.arange(a.shape[0])[:,None]
idx = (a*mask).argmax(0)

关于python - 在最小值之前的每列值中找到最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40671008/

相关文章:

python - 无法运行manage.py

python - pandas:如何将数据框的所有数字列转换为对数

python - Python中列值的累积和循环重置每年特定月份的值

Python 和 Pandas : a proper way to fetch data from a dataframe and create a new one

python - Scipy hstack 结果为 "TypeError: no supported conversion for types: (dtype(' float6 4'), dtype(' O'))"

python - OS X - Python 键盘记录器 - 双字母

python - hasattr 与函数

python - Scipy,差异进化

python - 读取文件时如何选择行分隔符?

python - 我如何 "randomly"选择对特定数字具有指定偏差的数字