【问题标题】:Assign values to numpy array from list indices从列表索引为 numpy 数组赋值
【发布时间】:2021-12-17 22:51:05
【问题描述】:

我有一个 numpy 数组和一个列表,比如说:

np_array = np.random.randint(0,3,(2,3))
np_array
array([[1, 1, 2],
       [2, 1, 2]])

indices_list:
[7,8,9]

并希望有一个 numpy 数组,该数组从列表的索引中获取其值(即,如果 np_array 的值为 2,则将 indices_list[2] 设置为新数组的值):

np_array_expected
array([[8, 8, 9],
       [9, 8, 9]])

我做了这个不成功的尝试:

np_array[indices_list]
Traceback (most recent call last):

  File "/tmp/ipykernel_27887/728354097.py", line 1, in <module>
    np_array[indices_list]

IndexError: index 7 is out of bounds for axis 0 with size 2


indices_list[np_array]
Traceback (most recent call last):

  File "/tmp/ipykernel_27887/265649000.py", line 1, in <module>
    indices_list[np_array]

TypeError: only integer scalar arrays can be converted to a scalar index

【问题讨论】:

  • 第一个失败,因为np_array 是索引集; indices_list 具有值。第二个失败,因为列表只能用单个值而不是数组来索引。如果indices_list 实际上是一个数组(或转换为一个数组),那么任务就很简单了。
  • 很高兴能帮上忙。不过,您介意接受我的回答吗?

标签: python list numpy indices


【解决方案1】:

这是我的迭代解决方案:

>>> arr = np.array([[1,1,2],[2,1,2]])
>>> indices_list = [7,8,9]
>>> for i in range(arr.shape[0]) :
...     for j in range(arr.shape[1]) :
...         arr[i][j] = indices_list[arr[i][j]]

>>> print(arr)

输出:

array([[8, 8, 9],
       [9, 8, 9]])

【讨论】:

    【解决方案2】:

    您只需要将列表也更改为 numpy 数组,然后就是简单的索引:

    np.array(indices_list)[np_array]
    

    做你想做的,我想。还是不行?

    【讨论】:

    • 是的,这行得通。谢谢。
    • 不客气。你介意接受我的回答吗?谢谢!
    【解决方案3】:

    这只是简单的索引:b[a],因为第二个数组也是 numpy 数组。

    输出:

    array([[8, 8, 9],
           [9, 8, 9]])
    

    【讨论】:

      猜你喜欢
      • 2014-01-15
      • 2015-06-16
      • 2023-03-26
      • 2014-01-08
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      相关资源
      最近更新 更多