詳解NumPy中np.where() 的兩種神奇用法
在數(shù)據(jù)科學(xué)和數(shù)值計(jì)算的世界里,NumPy 就像是一把瑞士軍刀,而 np.where() 無(wú)疑是其中最鋒利的工具之一。今天,我們將深入探索這個(gè)功能強(qiáng)大的函數(shù),學(xué)會(huì)如何用它優(yōu)雅地處理?xiàng)l件邏輯和數(shù)據(jù)選擇。
什么是 np.where()?
簡(jiǎn)單來(lái)說(shuō),np.where() 是 NumPy 中用于條件選擇和元素定位的核心函數(shù)。它有兩種主要用法:
- 三元條件替換:根據(jù)條件選擇不同值
- 索引定位:查找滿足條件的元素位置
讓我們通過(guò)實(shí)例來(lái)探索這兩種用法!
用法一:三元條件替換(條件 ? 值1 : 值2)
這是 np.where() 最常用的形式,語(yǔ)法為:np.where(condition, x, y)
- condition: 布爾數(shù)組(True/False)
- x: 當(dāng)條件為 True 時(shí)使用的值
- y: 當(dāng)條件為 False 時(shí)使用的值
基礎(chǔ)示例
import numpy as np # 創(chuàng)建示例數(shù)組 temperatures = np.array([22, 28, 15, 32, 18, 25]) # 標(biāo)記高溫和低溫 result = np.where(temperatures > 25, "高溫", "舒適") print(result) # 輸出:['舒適' '高溫' '舒適' '高溫' '舒適' '舒適']
實(shí)際應(yīng)用:成績(jī)分類(lèi)
scores = np.array([75, 92, 58, 81, 45, 67, 88])
# 根據(jù)分?jǐn)?shù)分類(lèi)
grade = np.where(scores >= 90, "A",
np.where(scores >= 80, "B",
np.where(scores >= 70, "C",
np.where(scores >= 60, "D", "F"))))
print(grade)
# 輸出:['C' 'A' 'F' 'B' 'F' 'D' 'B']
多條件組合
data = np.array([12, 25, 7, 18, 30, 5, 22]) # 組合條件:大于10且小于20 result = np.where((data > 10) & (data < 20), data, 0) print(result) # 輸出:[12 0 0 18 0 0 0] # 使用 | 表示 OR 條件 result = np.where((data < 10) | (data > 20), data, -1) print(result) # 輸出:[ -1 25 7 -1 30 5 22]
用法二:定位元素索引
當(dāng)我們只提供條件參數(shù)時(shí),np.where() 會(huì)返回滿足條件元素的索引。
語(yǔ)法:np.where(condition)
一維數(shù)組示例
arr = np.array([0, 5, 0, 8, 0, 3, 0]) # 找到非零元素的索引 non_zero_indices = np.where(arr != 0) print(non_zero_indices) # 輸出:(array([1, 3, 5]),) # 提取非零值 print(arr[non_zero_indices]) # 輸出:[5 8 3]
二維數(shù)組示例
matrix = np.array([[1, 0, 4],
[0, 5, 0],
[7, 0, 9]])
# 找到值大于3的元素位置
rows, cols = np.where(matrix > 3)
print("行索引:", rows) # 輸出:[0 1 2 2]
print("列索引:", cols) # 輸出:[2 1 0 2]
print("對(duì)應(yīng)值:", matrix[rows, cols]) # 輸出:[4 5 7 9]
實(shí)際應(yīng)用:圖像處理
# 創(chuàng)建一個(gè)簡(jiǎn)單的圖像矩陣 (5x5)
image = np.array([[120, 130, 40, 200, 210],
[30, 145, 255, 180, 10],
[220, 25, 30, 190, 200],
[100, 110, 120, 130, 140],
[50, 60, 70, 80, 90]])
# 找到高光區(qū)域(值>200)
highlight_rows, highlight_cols = np.where(image > 200)
print("高光像素位置:")
for r, c in zip(highlight_rows, highlight_cols):
print(f"({r}, {c}) - 值: {image[r, c]}")
# 輸出:
# (0, 3) - 值: 200
# (0, 4) - 值: 210
# (1, 2) - 值: 255
# (2, 0) - 值: 220
# (2, 3) - 值: 190 -> 注意:190不大于200,實(shí)際應(yīng)為 (2, 4): 200
# 更正:矩陣中 (2,4) 是200,所以應(yīng)包含
進(jìn)階技巧與注意事項(xiàng)
1. 廣播機(jī)制
np.where() 支持 NumPy 的廣播機(jī)制,使不同形狀的數(shù)組能夠一起工作:
# 二維條件與一維值組合 condition_2d = np.array([[True, False], [False, True]]) result = np.where(condition_2d, [10, 20], 0) print(result) # 輸出: # [[10 0] # [ 0 20]]
2. 直接修改滿足條件的值
data = np.array([5, 12, 8, 15, 3, 10]) # 將小于10的值替換為0 data[np.where(data < 10)] = 0 print(data) # 輸出:[ 0 12 0 15 0 10]
3. 多維度索引
對(duì)于三維或更高維數(shù)組,np.where() 同樣適用:
# 創(chuàng)建3x3x3數(shù)組
cube = np.random.randint(0, 10, (3, 3, 3))
# 找到所有大于8的元素
indices = np.where(cube > 8)
# 輸出三維索引
print("維度0:", indices[0])
print("維度1:", indices[1])
print("維度2:", indices[2])
# 訪問(wèn)這些元素
print("滿足條件的值:", cube[indices])
性能優(yōu)勢(shì)
與 Python 循環(huán)相比,np.where() 有顯著的性能優(yōu)勢(shì):
import time
large_array = np.random.rand(10**6)
# 使用循環(huán)
start = time.time()
result_loop = [x*2 if x > 0.5 else x/2 for x in large_array]
print("循環(huán)耗時(shí):", time.time() - start)
# 使用 np.where
start = time.time()
result_np = np.where(large_array > 0.5, large_array*2, large_array/2)
print("np.where耗時(shí):", time.time() - start)
測(cè)試結(jié)果(可能因機(jī)器而異):
循環(huán)耗時(shí): 0.45秒
np.where耗時(shí): 0.02秒
到此這篇關(guān)于詳解NumPy中np.where() 的兩種神奇用法的文章就介紹到這了,更多相關(guān)NumPy np.where() 用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決python給列表里添加字典時(shí)被最后一個(gè)覆蓋的問(wèn)題
今天小編就為大家分享一篇解決python給列表里添加字典時(shí)被最后一個(gè)覆蓋的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
Python列表去重的4種核心方法與實(shí)戰(zhàn)指南詳解
在Python開(kāi)發(fā)中,處理列表數(shù)據(jù)時(shí)經(jīng)常需要去除重復(fù)元素,本文將詳細(xì)介紹4種最實(shí)用的列表去重方法,有需要的小伙伴可以根據(jù)自己的需要進(jìn)行選擇2025-04-04
python消除序列的重復(fù)值并保持順序不變的實(shí)例
今天小編就為大家分享一篇python消除序列的重復(fù)值并保持順序不變的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
Python控制流之循環(huán)控制詳解(break, continue, pass)
本文將詳細(xì)介紹這三種循環(huán)控制語(yǔ)句的使用方法和最佳實(shí)踐,并附上一個(gè)綜合詳細(xì)的例子,幫助您全面掌握Python循環(huán)控制的用法,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-04-04
Win10里python3創(chuàng)建虛擬環(huán)境的步驟
在本篇文章里小編給大家整理的是一篇關(guān)于Win10里python3創(chuàng)建虛擬環(huán)境的步驟內(nèi)容,需要的朋友們可以學(xué)習(xí)參考下。2020-01-01
python實(shí)現(xiàn)多線程行情抓取工具的方法
當(dāng)我們實(shí)現(xiàn)了單線程,接下來(lái)就是實(shí)現(xiàn)多線程了,下面這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)多線程行情抓取工具的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-02-02
PyTorch實(shí)現(xiàn)FedProx聯(lián)邦學(xué)習(xí)算法
這篇文章主要為大家介紹了PyTorch實(shí)現(xiàn)FedProx的聯(lián)邦學(xué)習(xí)算法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

