【问题标题】:Dynamically index a specific element in an n-dimensional numpy array动态索引 n 维 numpy 数组中的特定元素
【发布时间】:2021-11-02 13:15:43
【问题描述】:

我有一个 n 维 bool numpy 数组。我想反转数组中随机项的布尔值。反转很容易,但我不确定如何最好地索引随机元素。我可以沿 n 维生成随机位置列表

indices = [np.random.randint(n) for n in array.shape]

但是,如何使用它来索引相应的元素? array[indices] 沿第一维获取索引处的元素。 array[*indices] 不起作用。我可以做类似的事情

a = array[indices[0]]
for index in indices[1:]:
    a = a[index]

但我想避免循环。有没有更优雅的解决方案?

【问题讨论】:

  • [(*indices,)] 可以正常工作

标签: python numpy indexing


【解决方案1】:

我知道这听起来太简单了,但是使用元组而不是列表作为索引。在Numpy docs 中有一些文档说明为什么会出现这种情况,但(至少对我而言)元组的重要性并不是很明显(尽管它非常清楚并且有一个很大的警告框)。

import numpy as np

np.random.seed(201)

A = np.random.choice(a=[False, True], size=(2,2))

# make it a Tuple
index = tuple(np.random.randint(n) for n in A.shape)

print(A)
# [[False True]
#  [False  True]]

print(index)
# (0, 1)

print(A[index])
# True

A[index] = ~A[index]
print(A)

# [[False  False]
#  [False  True]]

【讨论】:

  • 为什么不直接np.randint(a.shape)?
  • 是的,@MadPhysicist 这是一种更简洁的阵列制作方法。我想答案的要点是仍然需要变成一个元组才能按照OP想要的方式使用它并避免触发高级索引。
  • 谢谢,就是这样。我觉得这个语法不是很直观,但我现在肯定会记住它。
  • 这有助于我记住a[3,4,2] 真的是a[(3,4,2)]。索引是一个元组,每个维度有一个元素。创建元组的是逗号,() 并不总是必要的。
猜你喜欢
  • 1970-01-01
  • 2020-07-26
  • 2017-08-06
  • 2013-02-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多