对角线

这里,使用与之前不同的导入方法:

In [1]:

  1. import numpy as np

使用numpy中的函数前,需要加上 np.

In [2]:

  1. a = np.array([11,21,31,12,22,32,13,23,33])
  2. a.shape = 3,3
  3. a

Out[2]:

  1. array([[11, 21, 31],
  2. [12, 22, 32],
  3. [13, 23, 33]])

查看它的对角线元素:

In [3]:

  1. a.diagonal()

Out[3]:

  1. array([11, 22, 33])

可以使用偏移来查看它的次对角线,正数表示右移,负数表示左移:

In [4]:

  1. a.diagonal(offset=1)

Out[4]:

  1. array([21, 32])

In [5]:

  1. a.diagonal(offset=-1)

Out[5]:

  1. array([12, 23])

可以使用花式索引来得到对角线:

In [6]:

  1. i = [0,1,2]
  2. a[i, i]

Out[6]:

  1. array([11, 22, 33])

可以更新对角线的值:

In [7]:

  1. a[i, i] = 2
  2. a

Out[7]:

  1. array([[ 2, 21, 31],
  2. [12, 2, 32],
  3. [13, 23, 2]])

修改次对角线的值:

In [8]:

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

Out[8]:

  1. array([[ 2, 1, 31],
  2. [12, 2, 1],
  3. [13, 23, 2]])

In [9]:

  1. a[i + 1, i] = -1
  2. a

Out[9]:

  1. array([[ 2, 1, 31],
  2. [-1, 2, 1],
  3. [13, -1, 2]])

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/03-numpy/03.08-diagonals.ipynb