小编Die*_*oDZ的帖子

用python替换2D数组的对角线

我有以下二维数组

A=([[1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16])
Run Code Online (Sandbox Code Playgroud)

我想用数组替换主对角线

a = ([0,2,15,20])
Run Code Online (Sandbox Code Playgroud)

因此,结果必须是

A=([[0, 2, 3, 4],
    [5, 2, 7, 8],
    [9, 10, 15, 12],
    [13, 14, 15, 20])
Run Code Online (Sandbox Code Playgroud)

我尝试使用np.diag(a,k = 0),但是它不起作用,因为np.diag()创建了一个带有数组“ a”的对角2D数组。

有没有办法用numpy做到这一点?上面的例子是最简单的例子。我希望不仅可以更改邮件对角线,还可以更改所有对角线。

python arrays numpy diagonal

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

用python将两列矩阵乘以

我有两个矩阵:

A = [a11 a12 

     a21 a22]


B = [b11 b12
     b21 b22]
Run Code Online (Sandbox Code Playgroud)

我想将所有列(没有循环)相乘以获得矩阵:

C =[a11*b11   a11*b12   a12*b11   a12*b12
    a21*b21   a21*b22   a22*b21   a22*b22]
Run Code Online (Sandbox Code Playgroud)

我试过了

>>> C = np.prod(A,B,axis=0)
Run Code Online (Sandbox Code Playgroud)

但是prod不接受两个输入矩阵.既不是np.matrix.prod.

提前致谢.

python numpy matrix vectorization

4
推荐指数
1
解决办法
622
查看次数

使用python/numpy重塑数组

我想重塑以下数组:

>>> test
array([ 11.,  12.,  13.,  14.,  21.,  22.,  23.,  24.,  31.,  32.,  33.,
        34.,  41.,  42.,  43.,  44.])
Run Code Online (Sandbox Code Playgroud)

为了获得:

>>> test2
array([[ 11.,  12.,  21.,  22.],
       [ 13.,  14.,  23.,  24.],
       [ 31.,  32.,  41.,  42.],
       [ 33.,  34.,  43.,  44.]])
Run Code Online (Sandbox Code Playgroud)

我尝试过"重塑"之类的东西

>>> test.reshape(4,4)
    array([[ 11.,  12.,  13.,  14.],
           [ 21.,  22.,  23.,  24.],
           [ 31.,  32.,  33.,  34.],
           [ 41.,  42.,  43.,  44.]]) 
Run Code Online (Sandbox Code Playgroud)

 >>> test.reshape(2,2,2,2)
     array([[[[ 11.,  12.],
              [ 13.,  14.]],

              [[ 25.,  26.],
              [ 27., …
Run Code Online (Sandbox Code Playgroud)

python arrays numpy reshape

3
推荐指数
1
解决办法
348
查看次数

用python重塑数组

我有阵列

A = array([[  1.,   2.,   3.,  10.,  11.,  12.],
           [  4.,   5.,   6.,  13.,  14.,  15.],
           [  7.,   8.,   9.,  16.,  17.,  18.],
           [ 19.,  20.,  21.,  28.,  29.,  30.],
           [ 22.,  23.,  24.,  31.,  32.,  33.],
           [ 25.,  26.,  27.,  34.,  35.,  36.]])
Run Code Online (Sandbox Code Playgroud)

我想重塑它以获得

B = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]
Run Code Online (Sandbox Code Playgroud)

我试过了

>>> B = A.reshape(1,36)
array([[  1.,   2.,   3.,  10.,  11.,  12.,   4.,   5.,   6.,  13.,  14.,
         15.,   7.,   8.,   9.,  16.,  17.,  18.,  19.,  20.,  21.,  28.,
         29.,  30.,  22., …
Run Code Online (Sandbox Code Playgroud)

python arrays numpy reshape

2
推荐指数
1
解决办法
88
查看次数

标签 统计

numpy ×4

python ×4

arrays ×3

reshape ×2

diagonal ×1

matrix ×1

vectorization ×1