python - 如何以 python 方式获取 numpy argwhere 函数的最大值

标签 python numpy

我想使用 numpy argwhere 来查找我的数据中的最大值所在的位置。下面是一个示例集,描述了我在做什么:

bins = np.arange(10)
data = np.array([[6],[4],[8],[5]])
np.argwhere(bins<data)

array([[0, 0],
       [0, 1],
       [0, 2],
       [0, 3],
       [0, 4],
       [0, 5],
       [1, 0],
       [1, 1],
       [1, 2],
       [1, 3],
       [2, 0],
       [2, 1],
       [2, 2],
       [2, 3],
       [2, 4],
       [2, 5],
       [2, 6],
       [2, 7],
       [3, 0],
       [3, 1],
       [3, 2],
       [3, 3],
       [3, 4]])

我想从这些数据中得到的是

array([[0,5],
       [1,3],
       [2,7],
       [3,4]])

这可以通过 for 循环来完成,但我想知道是否有更 pythonic 的方法来做到这一点。

编辑:

我现在所做的是使用 Pandas 和 groupby。我仍然想知道这是否是最好的方法。

t = pd.DataFrame(np.argwhere(bins<data))
time = t.groupby(0)
time.max()

   1
0   
0  5
1  3
2  7
3  4

既然有了这个,我又遇到了一个新问题。假设我有另一组数据:

BigData = np.array([[0,1,2,3,4,5,6,7,8,9],
                   [0,1,2,3,4,5,6,7,8,9],
                   [0,1,2,3,4,5,6,7,8,9],
                   [0,1,2,3,4,5,6,7,8,9]])

如何使用我获得的数组

array([[0,5],
       [1,3],
       [2,7],
       [3,4]])

要放入这个新数据以获得 BigData 平均到第二列中的索引。即.E

(0+1+2+3+4) / 5
(0+1+2) / 3
(0+1+2+3+4+5+6) / 7
(0+1+2+3) / 4

将是 BigData 的返回,假设我们在第二列中获得了发生这种情况的索引值。

最佳答案

这是一个相当短的 Numpy 解决方案,它也非常快:

A = np.argwhere(bins<data)
print A[np.r_[A[1:,0] != A[:-1,0], True]]

关于python - 如何以 python 方式获取 numpy argwhere 函数的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24758813/

相关文章:

python - 是否可以将以一种方式堆叠的 Python 数组 reshape 为另一种堆叠类型?

python - 用 python 编写快速代码

python - 如何设置 Atom 的脚本来运行 Python 3.x 脚本?与 Windows 7 Pro x64 的组合可能是问题所在吗?

python - 如何解决安装基于 pyproject.toml 的项目所需的错误 : Could not build wheels for hdbscan,

python - 在字典中存储和检索图像 - python

python - 将每行最小的 2 个元素的 numpy 数组元素设置为零

python - 在 for 循环内删除 np 数组中的行

Python - 读取/解析二进制文件

python - 如何在python中制作一个验证卡安全码的程序?

Python 尝试在按数字排序后按字母顺序对列表进行排序