繁体   English   中英

numpy 数组索引:每行不同的列

[英]numpy array indexing: different columns of each row

我正在为 np 数组索引而苦苦挣扎。

假设我们有一个名为 a 的数组。

import numpy as np
a = np.ones((10000,100))

还有另一个名为idx的数组

idx = np.random.randint(low=0, high=a.shape[1], size=a.shape[0])

现在我想要做的是将idx中的 a 的每一列增加一,使用 for 循环,如下所示:

for k, i in enumerate(idx):
    a[k][i] += 1

无论如何使用索引来做到这一点,我知道例如

a[:,0] += 1

将 a 的每一列都增加一个,但是我们如何用不同的列来做到这一点呢?

我希望我的问题很清楚

你可以试试:

import numpy as np

a = np.ones((10000, 100))
a[:, 0] += 1
np.random.shuffle(np.transpose(a))
print(a)

解释:

  1. 导入必要的库:
import numpy as np
  1. 定义你的数组:
a = np.ones((10000, 100))
  1. 将数组第一列中的每个数字加1
a[:, 0] += 1
  1. 洗牌数组的每一列:
np.random.shuffle(np.transpose(a))

正如问题标题中所建议的,它可以通过数组索引来完成。

import numpy as np 
a = np.ones((20,10))                                                   

idx = np.random.randint(low=0, high=a.shape[1], size=a.shape[0])
idx                                                                    
# array([5, 0, 7, 3, 8, 7, 5, 1, 8, 8, 8, 8, 6, 9, 2, 4, 8, 4, 4, 7])

a[ np.arange( a.shape[0] ), idx ] += 1     # Array indexing

a  
# array([[1., 1., 1., 1., 1., 2., 1., 1., 1., 1.],
#        [2., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 2., 1., 1.],
#        [1., 1., 1., 2., 1., 1., 1., 1., 1., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 1., 2., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 2., 1., 1.],
#        [1., 1., 1., 1., 1., 2., 1., 1., 1., 1.],
#        [1., 2., 1., 1., 1., 1., 1., 1., 1., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 1., 2., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 1., 2., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 1., 2., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 1., 2., 1.],
#        [1., 1., 1., 1., 1., 1., 2., 1., 1., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 1., 1., 2.],
#        [1., 1., 2., 1., 1., 1., 1., 1., 1., 1.],
#        [1., 1., 1., 1., 2., 1., 1., 1., 1., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 1., 2., 1.],
#        [1., 1., 1., 1., 2., 1., 1., 1., 1., 1.],
#        [1., 1., 1., 1., 2., 1., 1., 1., 1., 1.],
#        [1., 1., 1., 1., 1., 1., 1., 2., 1., 1.]])

np.arange( a.shape[0] )对应于每一行,其中idx是列索引。

另一种方法是线性化索引(此算法与 MATLAB 兼容):

import numpy as np
a = np.ones((10,5))

col = np.random.randint(low=0, high=a.shape[1], size=a.shape[0])

# linearizing indices: idx = col + row * L; L -> total number of columns
idx = col + np.arange(a.shape[0]) * a.shape[1]
a[np.unravel_index(idx,a.shape)] += 1

print(a)

生成

[[2. 1. 1. 1. 1.]
 [1. 2. 1. 1. 1.]
 [1. 2. 1. 1. 1.]
 [1. 1. 1. 1. 2.]
 [1. 1. 1. 1. 2.]
 [1. 1. 1. 2. 1.]
 [2. 1. 1. 1. 1.]
 [2. 1. 1. 1. 1.]
 [1. 1. 1. 1. 2.]
 [2. 1. 1. 1. 1.]]

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM