小编A. *_*W. 的帖子

用于编辑numpy数组的一行解决方案?(蟒蛇)

我想制作一个numpy数组,其中包含在特定位置发生的值(1-3之间)的次数.例如,如果我有:

a = np.array([[1,2,3], 
              [3,2,1], 
              [2,1,3], 
              [1,1,1]])
Run Code Online (Sandbox Code Playgroud)

我想像这样回来一个数组:

[[[ 1  0  0]
  [ 0  1  0]
  [ 0  0  1]]

 [[ 0  0  1]
  [ 0  1  0]
  [ 1  0  0]]

 [[ 0  1  0]
  [ 1  0  0]
  [ 0  0  1]]

 [[ 1  0  0]
  [ 1  0  0]
  [ 1  0  0]]]
Run Code Online (Sandbox Code Playgroud)

数组告诉我1在第一个位置发生一次,2个在第二个位置发生一次,3个在第三个位置发生一次,1个在第四个位置发生一次,等等.后来,我将有更多的输入数组相同的维度,我想在这个计数数组中添加值的总和.

我现在的代码是:

a = np.array([[1,2,3],
              [3,2,1],
              [2,1,3],
              [1,1,1]])

cumulative = np.zeros((4,3,3))

for r in range(len(cumulative)):
    for c in range(len(cumulative[0])):
        cumulative[r, c, a[r,c]-1] +=1
Run Code Online (Sandbox Code Playgroud)

这确实给了我想要的输出.但是,我想将for循环压缩成一行,使用类似于这样的行: …

python arrays numpy

5
推荐指数
1
解决办法
96
查看次数

标签 统计

arrays ×1

numpy ×1

python ×1