繁体   English   中英

如果满足条件,则从数组中减去数字

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM