[英]Subtracting a number from an array if condition is met python
我在python中的if條件中面臨一個非常基本的問題。
數組current_img_list的尺寸為(500L,1)。 如果數字84459在此數組中,我想將其減去1。
index = np.random.randint(0,num_train-1,500)
# shape of current_img_list is (500L,1)
# values in index array is randomized
current_img_list = train_data['img_list'][index]
# shape of current_img_list is (500L,1)
if (any(current_img_list) == 82459):
i = np.where(current_img_list == 82459)
final_list = i-1
變量說明-train_data為dict類型。 它包含4個元素。 img_list是大小為(215375L,1)的元素之一。 num_train的值為215375, 索引的大小為(500L,1)
首先,我不知道此循環是否正常工作。 我嘗試了all()函數和numpy.where()函數,但沒有成功。 其次,我想不出一種方法,如何直接從82459的存儲索引中減去1,而不影響此數組中的其余值。
謝謝
在Python中循環遍歷比讓numpy的向量化運算符做事要慢得多:
import numpy as np
num_train = 90000 # for example
index = np.random.randint(0,num_train-1,500)
index[index == 82459] -= 1
我對這里要實現的目標感到有些困惑,但我會嘗試一下:
如果試圖從等於82459的數組中的任何地方減去1,則可能會通過for循環遍歷數組。 每次當前索引等於82459,只需將數字設置為該索引-= 1。
如果您需要更多幫助,請發布其余相關代碼,以便我進行調試。
current_img_list = np.array([1,2,3,82459,4,5,6])
i = np.where(current_img_list == 82459)
current_img_list[i] -= 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.