np.where函数如何使用?有哪些应用场景?
中等机器学习
答题要点
import numpy as np
# 三元表达式(if-then-else)
arr = np.array([1, 2, 3, 4, 5, 6])
result = np.where(arr > 3, 'big', 'small')
# ['small', 'small', 'small', 'big', 'big', 'big']
# 条件替换
data = np.array([10, -20, 30, -40, 50])
np.where(data < 0, 0, data) # 负数变0:[10, 0, 30, 0, 50]
# 返回索引(只传条件)
indices = np.where(arr > 3) # (array([3, 4, 5]),)
arr[indices] # array([4, 5, 6])
# 多条件嵌套
scores = np.array([85, 92, 78, 95, 60])
np.where(scores >= 90, 'A',
np.where(scores >= 80, 'B',
np.where(scores >= 60, 'C', 'F')))
# 二维数组
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
np.where(arr_2d > 3, 99, arr_2d) # >3的变99
# 多维度条件
row_idx, col_idx = np.where(arr_2d > 3)
# 行索引:[1, 1, 1],列索引:[0, 1, 2]
# 结合逻辑运算
arr = np.array([1, 2, 3, 4, 5])
np.where((arr > 2) & (arr < 5), arr * 2, arr) # [1, 2, 6, 8, 5]
# 条件计数
condition = arr > 3
count = np.where(condition)[0].size # 满足条件的个数
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题