在numpy中,可以将一维数组的索引设置为值。
import numpy as np
b = np.array([0, 0, 0, 0, 0])
indices = [1, 3]
b[indices] = 1
barray([0, 1, 0, 1, 0])我试图用多行和每一行的索引来实现这一点,以尽可能优雅的编程和高效的计算方式。例如
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
indices = [[1, 3], [0, 1], [0, 3]]期望的结果是
array([[0, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0]])我尝试了b[indices]和b[:,indices],但是它们导致了一个错误或不希望的结果。
从搜索的角度看,有几个工作环境,但在python中,每个循环都需要至少一个循环。
解决方案1:通过2d数组的每一行运行一个循环。这样做的好处是循环在python中运行,这个部分不会利用numpy的c++处理。
解决方案2:使用numpy put。退一步是put在输入数组的扁平版本上工作,因此索引也需要扁平,并根据行大小和行数进行更改,这将在python中使用双for循环。
解决方案3:put_along_axis似乎只能设置每行一个值,所以我需要对每一行的值数重复这个函数。
什么是计算上和编程上最优雅的解决方案?numpy能处理所有操作的地方吗?
发布于 2022-05-22 21:59:33
In 330: B= np.zeros((3,5),int)
要设置(3,2)列,行索引必须是(3,1)形状(通过广播进行匹配):
In [331]: indices = np.array([[1,3],[0,1],[0,3]])
In [332]: b[np.arange(3)[:,None], indices] = 1
In [333]: b
Out[333]:
array([[0, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0]])put along也做了同样的事情:
In [335]: b = np.zeros((3,5),int)
In [337]: np.put_along_axis(b, indices,1,axis=1)
In [338]: b
Out[338]:
array([[0, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0]])发布于 2022-05-22 21:02:45
在解决方案中构建每个维度中的索引,然后使用基本索引:
from itertools import chain
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
# Find the indices along the axis 0
y = np.arange(len(indices)).repeat(np.fromiter(map(len, indices), dtype=np.int_))
# Flatten the list and convert it to an array
x = np.fromiter(chain.from_iterable(indices), dtype=np.int_)
# Finaly set the items
b[y, x] = 1它甚至适用于具有可变大小子列表(如indices )的indices = [[1, 3], [0, 1], [0, 2, 3]]列表。如果您的indices列表总是包含每个子列表中相同数量的项,那么您可以使用以下代码(更有效):
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
indices = np.array(indices)
n, m = indices.shape
y = np.arange(n).repeat(m)
x = indices.ravel()
b[y, x] = 1发布于 2022-05-22 21:15:54
基于Jérôme's answer的简单一行(要求indices的所有项都是等长的):
>>> b[np.arange(np.size(indices)) // len(indices[0]), np.ravel(indices)] = 1
>>> b
array([[0, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0]])https://stackoverflow.com/questions/72341143
复制相似问题