具有二维值和索引数组的 numpy 二维数组赋值
numpy 2D array assignment with 2D value and indices arrays
我的目标是分配现有二维数组的值,或者创建一个新数组,使用两个相同形状的二维数组,一个有值,一个有索引,以便将相应的值分配给。
X = np.array([range(5),range(5)])
X
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Y= np.array([range(5), [2,3,4,1,0]])
Y
array([[0, 1, 2, 3, 4],
[2, 3, 4, 1, 0]])
我想要的输出是一个与 X 和 Y 形状相同的数组,X 的值在 Y 中相应行的索引中给出。这个结果可以通过以下方式遍历每一行来实现:
output = np.zeros(X.shape)
for i in range(X.shape[0]):
output[i][Y[i]] = X[i]
output
array([[ 0., 1., 2., 3., 4.],
[ 4., 3., 0., 1., 2.]])
有没有更有效的方法来应用这种赋值?
np.take(output, Y)
将 return 输出数组中的项分配给 X 的值,但我相信 np.take 不会产生对原始数组的引用,而是一个新数组。
for i in range(X.shape[0]):
output[i][Y[i]] = X[i]
等同于
I = np.arange(X.shape[0])[:, np.newaxis]
output[I, Y] = X
例如,
X = np.array([range(5),range(5)])
Y = np.array([range(5), [2,3,4,1,0]])
output = np.zeros(X.shape)
I = np.arange(X.shape[0])[:, np.newaxis]
output[I, Y] = X
产量
>>> output
array([[ 0., 1., 2., 3., 4.],
[ 4., 3., 0., 1., 2.]])
当循环迭代次数很少时,性能没有太大差异。
但是如果 X.shape[0]
很大,那么使用索引会快得多:
def using_loop(X, Y):
output = np.zeros(X.shape)
for i in range(X.shape[0]):
output[i][Y[i]] = X[i]
return output
def using_indexing(X, Y):
output = np.zeros(X.shape)
I = np.arange(X.shape[0])[:, np.newaxis]
output[I, Y] = X
return output
X2 = np.tile(X, (100,1))
Y2 = np.tile(Y, (100,1))
In [77]: %timeit using_loop(X2, Y2)
1000 loops, best of 3: 376 µs per loop
In [78]: %timeit using_indexing(X2, Y2)
100000 loops, best of 3: 15.2 µs per loop
我的目标是分配现有二维数组的值,或者创建一个新数组,使用两个相同形状的二维数组,一个有值,一个有索引,以便将相应的值分配给。
X = np.array([range(5),range(5)])
X
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Y= np.array([range(5), [2,3,4,1,0]])
Y
array([[0, 1, 2, 3, 4],
[2, 3, 4, 1, 0]])
我想要的输出是一个与 X 和 Y 形状相同的数组,X 的值在 Y 中相应行的索引中给出。这个结果可以通过以下方式遍历每一行来实现:
output = np.zeros(X.shape)
for i in range(X.shape[0]):
output[i][Y[i]] = X[i]
output
array([[ 0., 1., 2., 3., 4.],
[ 4., 3., 0., 1., 2.]])
有没有更有效的方法来应用这种赋值?
np.take(output, Y)
将 return 输出数组中的项分配给 X 的值,但我相信 np.take 不会产生对原始数组的引用,而是一个新数组。
for i in range(X.shape[0]):
output[i][Y[i]] = X[i]
等同于
I = np.arange(X.shape[0])[:, np.newaxis]
output[I, Y] = X
例如,
X = np.array([range(5),range(5)])
Y = np.array([range(5), [2,3,4,1,0]])
output = np.zeros(X.shape)
I = np.arange(X.shape[0])[:, np.newaxis]
output[I, Y] = X
产量
>>> output
array([[ 0., 1., 2., 3., 4.],
[ 4., 3., 0., 1., 2.]])
当循环迭代次数很少时,性能没有太大差异。
但是如果 X.shape[0]
很大,那么使用索引会快得多:
def using_loop(X, Y):
output = np.zeros(X.shape)
for i in range(X.shape[0]):
output[i][Y[i]] = X[i]
return output
def using_indexing(X, Y):
output = np.zeros(X.shape)
I = np.arange(X.shape[0])[:, np.newaxis]
output[I, Y] = X
return output
X2 = np.tile(X, (100,1))
Y2 = np.tile(Y, (100,1))
In [77]: %timeit using_loop(X2, Y2)
1000 loops, best of 3: 376 µs per loop
In [78]: %timeit using_indexing(X2, Y2)
100000 loops, best of 3: 15.2 µs per loop