python读取二维数组的行列数,numpy:获取二维数组最小值的列和行索引

本文探讨了如何使用numpy快速找到二维数组的最小值及其对应的行和列索引。通过比较`np.unravel_index`, `np.where` 和 自定义函数`find_min_idx` 的速度,发现自定义函数在某些情况下可能更快。最后推荐使用`divmod`函数结合`argmin`来获取最小值索引,以实现略微优化的性能。" 89677777,7431393,Python爬取股票代码教程,"['Python编程', '数据抓取', '网络爬虫', '金融数据']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

For example,

x = array([[1,2,3],[3,2,5],[9,0,2]])

some_func(x) gives (2,1)

I know one can do it by a custom function:

def find_min_idx(x):

k = x.argmin()

ncol = x.shape[1]

return k/ncol, k%ncol

However, I am wondering if there's a numpy built-in function that does this faster.

Thanks.

EDIT: thanks for the answers. I tested their speeds as follows:

%timeit np.unravel_index(x.argmin(), x.shape)

#100000 loops, best of 3: 4.67 µs per loop

%timeit np.where(x==x.min())

#100000 loops, best of 3: 12.7 µs per loop

%timeit find_min_idx(x) # this is using the custom function above

#100000 loops, best of 3: 2.44 µs per loop

Seems the custom function is actually faster than unravel_index() and where(). unravel_index() does similar things as the

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值