繁体   English   中英

从numpy数组python中提取元素

[英]Extract elements from a numpy array python

我有这个数组:

rel=np.array([1,0,0,1,1,0,1,0,1,0,0])

eta=np.array([2,3,10,16,4,3])

其中eta由对应于rel中0元素的元素组成。 换句话说,eta [0] = 2与rel [1] = 0相关,eta [1] = 3与rel [2] = 0相关,eta [2] = 10与rel [5] = 0相关, 等等。

我从rel中随机提取了一些元素,例如

rel_extract=np.array([1,0,0,1,0])

其中null元素位于第一,第二和第四索引。

考虑到eta_extract是用相同的eta规则制作的,如何使用eta中的值创建一个名为eta_extract的数组? 我猜eta_extract应该是

eta_extract=array([10,16,3])

非常感谢

您可以创建一个临时数组零,即rel的长度。 然后获得rel的索引为零。 然后将temp数组中的那些索引映射到rel值。 最后,生成rel一些随机索引,并在rel值为零的那些索引处获得eta的关联值。

# An array of zeros of length rel
tmp = np.zeros(rel.shape[0]) 
# Indices of rel that are zero
zero_rel_loc = np.where(rel == 0)
# Map the value from rel to tmp 
tmp[zero_rel_loc] = eta

# Generate a subset of size 5 of indices/values from rel
i = np.arange(rel.shape[0])
rand_ind = np.random.choice(i, 5, replace=False)
rand_eta_val = tmp[rand_ind]

# Remove the extra zeros
result = rand_eta_val[np.where(rand_eta_val != 0)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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