简体   繁体   English

numpy 函数将数组元素设置为给定索引列表的值

[英]numpy function to set elements of array to a value given a list of indices

I'm looking for a numpy function that will do the equivalent of:我正在寻找一个 numpy 函数,它可以执行以下操作:

indices = set([1, 4, 5, 6, 7])
zero    = numpy.zeros(10)
for i in indices:
    zero[i] = 42

You can just give it a list of indices:你可以给它一个索引列表:

indices = [1, 4, 5, 6, 7]
zero = numpy.zeros(10)
zero[indices] = 42

If you have an ndarray:如果你有一个 ndarray:

>>> x = np.zeros((3, 3, 3))
>>> y = [0, 9, 18]
>>> x
array([[[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]],

      [[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]],

      [[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]]])
>>> np.put(x, y,  1)
>>> x
array([[[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

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

相关问题 如何有效地从numpy数组中提取由其索引给出的元素列表? - How to extract a list of elements given by their indices from a numpy array efficiently? 将索引的 function 应用于 numpy 数组的所有元素 - Apply a function of the indices to all elements of a numpy array 如何在具有给定起点索引的numpy数组中选择元素 - How to select elements in numpy array with given starting point indices numpy:在给定递增索引的情况下递增数组的元素 - Numpy: increment elements of an array given the indices required to increment 使用给定的一组索引访问 numpy 数组的连续行 - Accessing the sequential rows of a numpy array with a given set of indices 查找值在给定集中的numpy向量的所有索引 - Find all indices of numpy vector whose value is in a given set 使用给定的索引数组从3d numpy数组中删除numpy数组元素 - Deleting numpy array elements from a 3d numpy array with given array of indices 访问不在给定索引列表中的 NumPy 数组元素 - Accessing NumPy array elements not in a given index list 笛卡尔积可获取一组索引以指向NumPy数组中的唯一元素 - Cartesian product to get set of indices to point to unique elements in NumPy array 通过使用元组列表作为python中的索引在numpy数组中获取元素 - Getting elements within a numpy array by using a list of tuples as indices in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM