简体   繁体   English

给定(固定)元素的索引时创建一个numpy数组

[英]Create a numpy array when indexes of (fixed) elements are given

I have a numpy array of indexes eg [1,3,12] . 我有一个numpy的索引数组,例如[1,3,12] I want to create another array from this such that at these indexes, I get a non-zero elements eg 1. So in this case, with input [1,3,12] , I should get [0,1,0,1,0,0,0,0,0,0,0,0,1] . 我想从中创建另一个数组,以便在这些索引处获得一个非零元素,例如1。因此,在这种情况下,使用输入[1,3,12] ,我应该得到[0,1,0,1,0,0,0,0,0,0,0,0,1] I can do it in a for loop, is there a short numpy function to achieve this? 我可以在for循环中执行此操作,是否有一个短的numpy函数来实现这一目标?

With numpy you can index with lists directly: 使用numpy,您可以直接索引列表:

a = [1,3,12]
vector = numpy.zeros(shape=max(a) + 1)
vector[a] = 1

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

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