np.where()与object.argmax()的区别

本文详细介绍了 NumPy 中的 np.where() 和 argmax() 函数。np.where() 根据条件返回数组元素的值或替换值,当仅提供条件时,返回满足条件的索引。argmax() 则根据轴的方向寻找最大值的索引,当 axis=None 时,会在整个数组中查找。两者的最大区别在于处理相同数据时,np.where() 返回所有匹配索引,而 argmax() 只返回最小索引。
摘要由CSDN通过智能技术生成

一、np.where(condition,x=None,y=None)

        1、当condition为True时,将执行x,否则执行y

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,])
b = np.where(a > 6,a * 2,a)
print(b)

         2、特殊情况下,当只有condition时,将返回满足condition的数据索引。注意,返回的数据类型为元组(index,type)。

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,])
b = np.where(a > 6)
print(b)

 

         当原数据为多维时,返回也为多维数组的索引。(以二维为例,第一维为行索引,第二维为列索引)

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12]).reshape(3,4)
print(a)
b = np.where(a > 6)
print(b)

 二、object.argmax(axis=None)

        以参数axis为指引,决定按哪一个方向寻找最大值。当参数不指定时,默认先平铺所有数据,后寻找最大值。

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12]).reshape(3,4)
print(a)

#axis = 0,按列方向寻找最大索引
axis_0 = a.argmax(axis=0)
print('--axis=0---')
print(axis_0)

#axis = 1,按行方向寻找最大索引
axis_1 = a.argmax(axis=1)
print('--axis=1---')
print(axis_1)

#axis=None
axis_none = a.argmax()
print('--axis=1---')
print(axis_none)

 

 三、两者最大区别

        当待寻找对象存在相同数据时,前者p.where(condition)可以返回多个索引而后者object.argmax()只能返回对应相同数据中所有索引的最小值。 

import numpy as np
a = np.array([1, 2, 5, 4, 5, 5])
print(a)

b_where = np.where(a == 5)
print(b_where)
print('--------')
b_argmax = a.argmax()
print(b_argmax)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rc小小白…

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值