Lesson5——NumPy 创建数组

NumPy 教程目录

前言

  ndarray 数组除了可以使用底层 ndarray 构造器来创建外,也可以通过以下几种方式来创建。

1 From shape or value

MethodReturn
empty(shape[, dtype, order, like]) 返回给定形状和类型、没初始化的新数组。
empty_like(prototype[, dtype, order, subok, ...]) 返回一个与给定数组具有相同形状和类型的新数组。
eye(N[, M, k, dtype, order, like]) 返回一个二维数组,其中对角线为 1,其他位置为 0。
identity(n[, dtype, like]) 返回标识数组。
ones(shape[, dtype, order, like]) 返回一个给定形状和类型的新数组,元素用 1 填充。
ones_like(a[, dtype, order, subok, shape]) 返回与给定数组具有相同形状和类型的全 1 数组。
zeros(shape[, dtype, order, like]) 返回与给定数组具有相同形状和类型的零数组。
zeros_like(a[, dtype, order, subok, shape]) 返回给定形状和类型的新数组,用 0 填充。
full(shape, fill_value[, dtype, order, like]) 返回一个给定形状和类型的新数组,用 fill_value 填充。
full_like(a, fill_value[, dtype, order, ...]) 返回与给定数组具有相同形状和类型的完整数组。

1.1 numpy.empty

  • numpy.empty(shapedtype=floatorder='C'*like=None)
  • 返回给定形状和类型、没初始化的新数组。

Examples:

>>>np.empty((2,2))
array([[2.12199579e-314, 8.01304298e+262],
       [4.32801506e-321, 9.90972035e-312]])
>>>np.empty([2,2])
array([[2.12199579e-314, 8.01304298e+262],
       [4.32801506e-321, 9.90972035e-312]])
>>>np.empty(2)
array([-1.93143376e+130,  1.06764749e+266])
>>>np.empty([2,2],dtype =int )
array([[   1068,       0],
       [      0, 2752558]])

1.2 numpy.empty_like

  • numpy.empty_like(prototypedtype=Noneorder='K'subok=Trueshape=None)
  • 返回一个与给定数组具有相同形状和类型的新数组。

Examples:

a = np.arange(6).reshape(-1,3)
print(a)
b = np.empty_like(a)
print(b)
#输出结果
[[0 1 2]
 [3 4 5]]
[[ 577662825 1630937658 1697658169]
 [ 909588272  942957872  842609765]]

1.3 numpy.eye

  • numpy.eye(NM=Nonek=0dtype=<class 'float'>order='C'*like=None)
  • 返回一个二维数组,其中对角线为 1,其他位置为 0。

Examples:

>>>np.eye(3, dtype=int)
array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 1]])
>>>np.eye(3, k=1)
array([[0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 0.]])
>>>np.eye(3, k=-1)
array([[0., 0., 0.],
       [1., 0., 0.],
       [0., 1., 0.]])
>>>np.eye(3, dtype=np.float32)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]], dtype=float32)

1.4 numpy.identity

  • numpy.identity(ndtype=None*like=None)
  • 返回标识数组。

Examples:

>>>np.identity(3)
array([[1.,  0.,  0.],
       [0.,  1.,  0.],
       [0.,  0.,  1.]])

1.5 numpy.ones

  • numpy.ones(shape, dtype=None, order='C', *, like=None)
  • 返回一个给定形状和类型的新数组,元素用 1 填充。

Examples:

>>>np.ones(5)
array([1., 1., 1., 1., 1.])
>>>np.ones((5,), dtype=int)
array([1, 1, 1, 1, 1])
>>>np.ones(5,dtype=int)
array([1, 1, 1, 1, 1])
>>>np.ones((2, 1))
array([[1.],
       [1.]])
>>>np.ones((2,2))
array([[1.,  1.],
       [1.,  1.]])

1.6 numpy.ones_like

  • numpy.ones_like(a, dtype=None, order='K', subok=True, shape=None)
  • 返回与给定数组具有相同形状和类型的全 1 数组。

Examples:

>>>x = np.arange(6).reshape(2,3)
>>>np.ones_like(np.arange(6).reshape(2,3))
array([[1, 1, 1],
[1, 1, 1]])

>>>x = np.arange(6).reshape(2,3)
>>>np.ones_like(x,dtype=np.float64)
array([[1., 1., 1.],
[1., 1., 1.]])

>>>x = np.arange(6).reshape(2,3)
>>>np.ones_like(x,float)
array([[1., 1., 1.],
[1., 1., 1.]])

1.7 numpy.zeros

  • numpy.zeros(shape, dtype=float, order='C', *, like=None)
  • 返回给定形状和类型的新数组,用 0 填充。

Examples:

>>>np.zeros(5)
array([ 0., 0., 0., 0., 0.])

>>>np.zeros((5,), dtype=int)
array([0, 0, 0, 0, 0])

>>>np.zeros((2, 1))
array([[ 0.],
[ 0.]])

>>>s = (2,2)
>>>np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])

>>>np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)],
dtype=[('x', '<i4'), ('y', '<i4')])

1.8 numpy.zeros_like

  • numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None)
  • 返回与给定数组具有相同形状和类型的零数组。

Examples:

>>>x = np.arange(6).reshape((2,3))
>>>np.zeros_like(x)
array([[0, 0, 0],
       [0, 0, 0]])

>>>np.zeros_like(x,dtype=float)
array([[0., 0., 0.],
       [0., 0., 0.]])

>>>y = np.arange(3, dtype=float)
>>>np.zeros_like(y)
array([0.,  0.,  0.])

1.9 numpy.full

  • numpy.full(shape, fill_value, dtype=None, order='C', *, like=None)
  • 返回一个给定形状和类型的新数组,用 fill_value 填充。

Examples:

>>>np.full((2,2),3)
array([[3, 3],
       [3, 3]])

>>>np.full([2,2],3,dtype = float)
array([[3., 3.],
       [3., 3.]])

>>>np.full((2,2),[1,2])
array([[1, 2],
       [1, 2]])

1.10 numpy.full_like

  • numpy.full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None)
  • 返回与给定数组具有相同形状和类型的完整数组。

Examples:

>>>x = np.arange(6,dtype = int).reshape((2,3))
>>>np.full_like(x,1)
array([[1, 1, 1],
       [1, 1, 1]])

>>>np.full_like(x,0.1)
array([[0, 0, 0],
       [0, 0, 0]])

>>>x = np.arange(6,dtype =np.double).reshape((2,3))
>>>np.full_like(x,0.1)
array([[0.1, 0.1, 0.1],
       [0.1, 0.1, 0.1]])

>>>np.full_like(x,1)
array([[1., 1., 1.],
       [1., 1., 1.]])

>>>np.full_like(x,np.nan)
array([[nan, nan, nan],
       [nan, nan, nan]])

2 From existing data

MethodReturn
array(object[, dtype, copy, order, subok, ...]) 创建一个数组。
asarray(a[, dtype, order, like]) 将输入转换为数组。
asanyarray(a[, dtype, order, like]) 将输入转换为矩阵。
ascontiguousarray(a[, dtype, like]) 在内存中返回一个连续数组 (ndim >= 1)(C 顺序)。
asmatrix(data[, dtype]) 将输入转换为矩阵。
copy(a[, order, subok]) 返回给定对象的数组副本。
frombuffer(buffer[, dtype, count, offset, like]) 将缓冲区解释为一维数组。
fromfile(file[, dtype, count, sep, offset, like]) 从文本或二进制文件中的数据构造一个数组。
fromfunction(function, shape, *[, dtype, like]) 通过在每个坐标上执行一个函数来构造一个数组。
fromiter(iter, dtype[, count, like]) 从可迭代对象创建一个新的一维数组。
fromstring(string[, dtype, count, like]) 从字符串中的文本数据初始化的新一维数组。
loadtxt(fname[, dtype, comments, delimiter, ...]) 从文本文件加载数据。

2.1 numpy.array

  • numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)
  • 创建一个数组。

Examples:

>>>np.array([1,2,3])
array([1, 2, 3])

>>>np.array([1,2],dtype = float)
array([1., 2.])

>>>np.array([[1,2],[3,4]])
array([[1, 2],
       [3, 4]])

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

>>>np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j,  2.+0.j,  3.+0.j])

>>>x = np.array([(1,2),(3,4)],dtype = [('col1','i1'),('col2','i2')])
>>>x['col1']
array([1, 3], dtype=int8)

>>>np.array(np.mat('1 2; 3 4'))
array([[1, 2],
       [3, 4]])

>>>np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
        [3, 4]])

2.2 numpy.asarray

  • numpy.asarray(a, dtype=None, order=None, *, like=None)
  • 将输入转换为数组。

Examples:

#Convert a list into an array:
>>>a = [1, 2]
>>>np.asarray(a)
array([1, 2])

#Existing arrays are not copied:
>>>a = np.array([1, 2])
>>>np.asarray(a) is a
True

#If dtype is set, array is copied only if dtype does not match:
>>>a = np.array([1, 2], dtype=np.float32)
>>>np.asarray(a, dtype=np.float32) is a
True
>>>np.asarray(a, dtype=np.float64) is a
False

#Contrary to asanyarray, ndarray subclasses are not passed through:
>>>issubclass(np.recarray, np.ndarray)
True
>>>a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
>>>np.asarray(a) is a
False
>>>np.asanyarray(a) is a
True

2.3 numpy.ascontiguousarray

  • numpy.ascontiguousarray(a, dtype=None, *, like=None)
  • 在内存中返回一个连续数组 (ndim >= 1)(C 顺序)。

Examples:

>>>x = np.arange(6).reshape(2,3)
>>>np.ascontiguousarray(x, dtype=np.float32)
array([[0., 1., 2.],
       [3., 4., 5.]], dtype=float32)
>>>x.flags['C_CONTIGUOUS']
True

2.4 numpy.asanyarray

  • numpy.asanyarray(a, dtype=None, order=None, *, like=None)
  • 将输入转换为 ndarray,但传递 ndarray 子类。

Examples :

>>>np.asanyarray([1,2])
array([1, 2])

>>>a = np.array([[1,2],[3,4]],dtype = 'f4,i4').view(np.recarray)
>>>np.asanyarray(a) is a 
True

2.5 numpy.asmatrix

  • numpy.asmatrix(data, dtype=None)
  • 将输入转换为矩阵。

 Examples:

>>>x  = np.array([[1,2,3],[4,5,6]])
>>>y = np.asmatrix(x)
>>>y
matrix([[1, 2, 3],
        [4, 5, 6]])

>>>x[0,0] = 100
>>>y
matrix([[100,   2,   3],
        [  4,   5,   6]])

>>>y[0,0] = 1
>>>x
array([[1, 2, 3],
       [4, 5, 6]])

2.6 numpy.copy

  • numpy.copy(a, order='K', subok=False)
  • 返回给定对象的数组副本。

Examples1:

>>>x = np.array([1,2])
>>>y = x
>>>y
array([1, 2])

>>>z = np.copy(x)
>>>z
array([1, 2])

>>>x [0] =100
>>>print(y)
>>>print(z)
[100   2]
[1 2]

Examples2:

>>>a = np.array([1, 2, 3])
>>>a.flags["WRITEABLE"] = False
>>>b = np.copy(a)
>>>b.flags["WRITEABLE"]
True
>>>b[0] = 3
>>>b
array([3, 2, 3])

Examples3:

>>>import copy
>>>a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>>c = copy.deepcopy(a)
>>>c[2][0] = 10
c
>>>array([1, 'm', list([10, 3, 4])], dtype=object)
a
>>>array([1, 'm', list([2, 3, 4])], dtype=object)

2.7 numpy.frombuffer

  • numpy.frombuffer(buffer, dtype=float, count=- 1, offset=0, *, like=None)
  • 将缓冲区解释为一维数组。

Examples1:

>>>s = b'Hello world'
>>>np.frombuffer(s,dtype = 'S1',count=5,offset = 6)
array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')

2.8 numpy.fromfile

  • umpy.fromfile(file, dtype=float, count=- 1, sep='', offset=0, *, like=None)
  • 从文本或二进制文件中的数据构造一个数组。

  Example:构建数据

dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]),
               ('temp', float)])
x = np.zeros((1,),dtype = dt)
x['time']['min'] = 10
x['temp'] = 10
x
#输出结果
array([((10, 0), 10.)],
      dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])

  Example1:使用 np.fromflie() 函数

fname = tempfile.mkstemp()[1]
x.tofile(fname)
np.fromfile(fname, dtype=dt)
#输出结果
array([((10, 0), 10.)],
      dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])

  Example2:使用 np.save() np.load() 函数

fname = tempfile.mkstemp()[1]
x.tofile(fname)
np.save(fname,x)
np.load(fname+'.npy')
#输出结果
array([((10, 0), 10.)],
      dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])

2.9 numpy.fromfunction

  • numpy.fromfunction(function, shape, *, dtype=<class 'float'>, like=None, **kwargs)
  • 通过在每个坐标上执行一个函数来构造一个数组。

Examples:

np.fromfunction(lambda i, j: i, (3, 3), dtype=float)
#输出结果
array([[0., 0., 0.],
       [1., 1., 1.],
       [2., 2., 2.]])

np.fromfunction(lambda i, j: j, (3, 3), dtype=float)
#输出结果
array([[0., 1., 2.],
       [0., 1., 2.],
       [0., 1., 2.]])

np.fromfunction(lambda i, j: i+j, (3, 3), dtype=float)
#输出结果
array([[ True, False, False],
       [False,  True, False],
       [False, False,  True]])

np.fromfunction(lambda i, j: i==j, (3, 3), dtype=float)
#输出结果
array([[ True, False, False],
       [False,  True, False],
       [False, False,  True]])

 2.10 numpy.fromiter

  • numpy.fromiter(iter, dtype, count=- 1, *, like=None)
  • 从可迭代对象创建一个新的一维数组。

Examples:

iterable = (x*x for x in range(3))
np.fromiter(iterable,float)
#输出结果
array([0., 1., 4.])

iterable = [1,2,3]
np.fromiter(iterable,float)
#输出结果
array([1., 2., 3.])

2.11 numpy.fromstring

  • numpy.fromstring(string, dtype=float, count=- 1, *, sep, like=None)
  • 从字符串中的文本数据初始化的新一维数组。

Examples:

np.fromstring('1,2',dtype = int,sep =',')
#输出结果
array([1, 2])
np.fromstring('1 2', dtype=int, sep=' ')
#输出结果
array([1, 2])
np.fromstring('1 2', dtype=int, sep=',')
#输出结果
array([1])

2.12 numpy.loadtxt

  • numpy.loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, quotechar=None, like=None)
  • 从文本文件加载数据。
Example1:
from io import StringIO   # StringIO behaves like a file object
c = StringIO("0 1\n2 3")
np.loadtxt(c)
#输出结果
array([[0., 1.],
       [2., 3.]])

Example2:

d = StringIO("M 21 72\nF 35 58")
np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
                     'formats': ('S1', 'i4', 'f4')})
#输出结果
array([(b'M', 21, 72.), (b'F', 35, 58.)],
      dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])

Example3:

s = StringIO("1.618, 2.296\n3.141, 4.669\n")
conv = {
    0: lambda x: np.floor(float(x)),  # conversion fn for column 0
    1: lambda x: np.ceil(float(x)),  # conversion fn for column 1
}
np.loadtxt(s, delimiter=",", converters=conv)
#输出结果
array([[1., 3.],
       [3., 5.]])

  More example

3 Numerical ranges

MethodReturn
arange([start,] stop, step,) 在给定的间隔内返回均匀间隔的值。
linspace(start, stop[, num, endpoint, ...]) 在指定的间隔内返回均匀分布的数字。
logspace(start, stop[, num, endpoint, base, ...]) 返回在对数刻度上均匀分布的数字。
geomspace(start, stop[, num, endpoint, ...]) 返回在对数尺度上均匀分布的数字(几何级数)。
meshgrid(*xi[, copy, sparse, indexing]) 从坐标向量返回坐标矩阵。
mgrid nd_grid 实例,它返回一个密集的多维“网格”。
ogrid nd_grid 实例,它返回一个开放的多维“网格”。

3.1 numpy.arange

 

  • numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)
  • 在给定的间隔内返回均匀间隔的值。

Examples:

np.arange(3)
#输出结果
array([0, 1, 2])

np.arange(3.0)
#输出结果
array([ 0.,  1.,  2.])

np.arange(3,7)
#输出结果
array([3, 4, 5, 6])

np.arange(3,7,2)
#输出结果
array([3, 5])

3.2 numpy.linspace

  • numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
  • 在指定的间隔内返回均匀分布的数字。

Examples:

np.linspace(2.0, 3.0, num=5)
#输出结果
array([2.  , 2.25, 2.5 , 2.75, 3.  ])

np.linspace(2.0, 3.0, num=5, endpoint=False)#不包括终点
#输出结果
array([2. ,  2.2,  2.4,  2.6,  2.8])

np.linspace(2.0, 3.0, num=5, retstep=True)#以元组形式返回array和步长
#输出结果
(array([2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)

Graphical illustration:

import matplotlib.pyplot as plt
N = 8
y = np.zeros(N)
x1 = np.linspace(0, 10, N, endpoint=True)
x2 = np.linspace(0, 10, N, endpoint=False)
plt.plot(x1, y, 'o')
plt.plot(x2, y + 0.5, 'o')
plt.ylim([-0.5, 1])
(-0.5, 1)
plt.show()

输出结果:

  

3.3 numpy.logspace

  • numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)
  • 返回在对数刻度上均匀分布的数字。

Examples:

np.logspace(2.0, 3.0, num=4)
#输出结果
array([ 100.        ,  215.443469  ,  464.15888336, 1000.        ])

np.logspace(2.0, 3.0, num=4, endpoint=False)
#输出结果
array([100.        ,  177.827941  ,  316.22776602,  562.34132519])

np.logspace(2.0, 3.0, num=4, base=2.0)
#输出结果
array([4.        ,  5.0396842 ,  6.34960421,  8.        ])

Graphical illustration:

import matplotlib.pyplot as plt
N = 10
x1 = np.logspace(0.1, 1, N, endpoint=True)
x2 = np.logspace(0.1, 1, N, endpoint=False)
y = np.zeros(N)
plt.plot(x1, y, 'o')
plt.plot(x2, y + 0.5, 'o')
plt.ylim([-0.5, 1])
(-0.5, 1)
plt.show()

输出结果:

  

3.4 numpy.geomspace

  • numpy.geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)
  • 返回在对数尺度上均匀分布的数字(几何级数)。

Examples:

np.geomspace(1, 1000, num=4)
#输出结果
array([    1.,    10.,   100.,  1000.])

np.geomspace(1, 1000, num=3, endpoint=False)
#输出结果
array([   1.,   10.,  100.])

np.geomspace(1, 1000, num=4, endpoint=False)
#输出结果
array([   1.        ,    5.62341325,   31.6227766 ,  177.827941  ])

np.geomspace(1, 256, num=9)
#输出结果
array([   1.,    2.,    4.,    8.,   16.,   32.,   64.,  128.,  256.])

Examples:

np.geomspace(1000, 1, num=4)
#输出结果
array([1000.,  100.,   10.,    1.])

np.geomspace(-1000, -1, num=4)
#输出结果
array([-1000.,  -100.,   -10.,    -1.])

np.geomspace(1j, 1000j, num=4)  # Straight line
#输出结果
array([0.   +1.j, 0.  +10.j, 0. +100.j, 0.+1000.j])

np.geomspace(-1+0j, 1+0j, num=5)  # Circle
#输出结果
array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j,
        6.12323400e-17+1.00000000e+00j,  7.07106781e-01+7.07106781e-01j,
        1.00000000e+00+0.00000000e+00j])

Graphical illustration of endpoint parameter:

import matplotlib.pyplot as plt
N = 10
y = np.zeros(N)
plt.semilogx(np.geomspace(1, 1000, N, endpoint=True), y + 1, 'o')
plt.semilogx(np.geomspace(1, 1000, N, endpoint=False), y + 2, 'o')
plt.axis([0.5, 2000, 0, 3])
[0.5, 2000, 0, 3]
plt.grid(True, color='0.7', linestyle='-', which='both', axis='both')
plt.show()

输出结果:

  

3.5 numpy.meshgrid

  • numpy.meshgrid(*xi, copy=True, sparse=False, indexing='xy')
  • 从坐标向量返回坐标矩阵。

Examples:

nx, ny = (3, 2)
x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
xv, yv = np.meshgrid(x, y)
xv
#输出结果
array([[0. , 0.5, 1. ],
       [0. , 0.5, 1. ]])
yv
#输出结果
array([[0.,  0.,  0.],
       [1.,  1.,  1.]])

xv, yv = np.meshgrid(x, y, sparse=True)  # make sparse output arrays
xv
#输出结果
array([[0. ,  0.5,  1. ]])

yv
#输出结果
array([[0.],
       [1.]])

Example:

x = np.linspace(-5, 5, 101)
y = np.linspace(-5, 5, 101)
# full coordinate arrays
xx, yy = np.meshgrid(x, y)
zz = np.sqrt(xx**2 + yy**2)
xx.shape, yy.shape, zz.shape
#输出结果
((101, 101), (101, 101), (101, 101))
# sparse coordinate arrays
xs, ys = np.meshgrid(x, y, sparse=True)
zs = np.sqrt(xs**2 + ys**2)
xs.shape, ys.shape, zs.shape
#输出结果
((1, 101), (101, 1), (101, 101))
np.array_equal(zz, zs)
#输出结果
True

Example:

import matplotlib.pyplot as plt
h = plt.contourf(x, y, zs)
plt.axis('scaled')
plt.colorbar()
plt.show()

输出结果

  

3.6 numpy.mgrid

  • numpy.mgrid = <numpy.lib.index_tricks.MGridClass object>
  • nd_grid 实例,它返回一个密集的多维“网格”。

Example:

np.mgrid[0:5, 0:5]
#输出结果
array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4]],
       [[0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4]]])
np.mgrid[-1:1:5j]
#输出结果
array([-1. , -0.5,  0. ,  0.5,  1. ])

3.7 numpy.ogrid

  • numpy.ogrid = <numpy.lib.index_tricks.OGridClass object>
  • nd_grid 实例,它返回一个开放的多维“网格”。

Example:

from numpy import ogrid
ogrid[-1:1:5j]
#输出结果
array([-1. , -0.5,  0. ,  0.5,  1. ])
ogrid[0:5,0:5]
#输出结果
[array([[0],
        [1],
        [2],
        [3],
        [4]]), array([[0, 1, 2, 3, 4]])]

4 Building matrices

MethodReturn
diag(v[, k]) 提取对角线或构造对角线数组。
diagflat(v[, k]) 创建一个二维数组,将扁平化的输入作为对角线。
tri(N[, M, k, dtype, like]) 一个数组,在给定对角线处和下方都有一个,在其他地方有零。
tril(m[, k]) 数组的下三角形。
triu(m[, k]) 数组的上三角形。
vander(x[, N, increasing]) 生成范德蒙德矩阵。

4.1 numpy.diag

  • numpy.diag(v, k=0)
  • 提取对角线或构造对角线数组。

Examples

x = np.arange(9).reshape((3,3))
x
#输出结果
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

np.diag(x)
#输出结果
array([0, 4, 8])

np.diag(x, k=1)
#输出结果
array([1, 5])

np.diag(x, k=-1)
#输出结果
array([3, 7])

np.diag(np.diag(x))
#输出结果
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])

4.2 numpy.diagflat

  • numpy.diagflat(v, k=0)
  • 创建一个二维数组,将扁平化的输入作为对角线。

Examples

np.diagflat([[1,2], [3,4]])
#输出结果
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])

np.diagflat([1,2], 1)
#输出结果
array([[0, 1, 0],
       [0, 0, 2],
       [0, 0, 0]])

4.3 numpy.tri

  • numpy.tri(N, M=None, k=0, dtype=<class 'float'>, *, like=None)
  • 一个数组,在给定对角线处和下方都有一个,在其他地方有零。

Examples

np.tri(3, 5, 2, dtype=int)
#输出结果
array([[1, 1, 1, 0, 0],
       [1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1]])

np.tri(3, 5, -1)
#输出结果
array([[0.,  0.,  0.,  0.,  0.],
       [1.,  0.,  0.,  0.,  0.],
       [1.,  1.,  0.,  0.,  0.]])

4.4 numpy.tril

  • numpy.tril(m, k=0)
  • 数组的下三角形。

Example1:

np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
#输出结果
array([[ 0,  0,  0],
       [ 4,  0,  0],
       [ 7,  8,  0],
       [10, 11, 12]])

Example2:

np.tril(np.arange(3*4*5).reshape(3, 4, 5))
#输出结果
array([[[ 0,  0,  0,  0,  0],
        [ 5,  6,  0,  0,  0],
        [10, 11, 12,  0,  0],
        [15, 16, 17, 18,  0]],
       [[20,  0,  0,  0,  0],
        [25, 26,  0,  0,  0],
        [30, 31, 32,  0,  0],
        [35, 36, 37, 38,  0]],
       [[40,  0,  0,  0,  0],
        [45, 46,  0,  0,  0],
        [50, 51, 52,  0,  0],
        [55, 56, 57, 58,  0]]])

4.5 numpy.triu

  • numpy.triu(m, k=0)
  • 数组的上三角形。

Example1:

np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
#输出结果
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 0,  8,  9],
       [ 0,  0, 12]])

Example2:

np.triu(np.arange(3*4*5).reshape(3, 4, 5))
#输出结果
array([[[ 0,  1,  2,  3,  4],
        [ 0,  6,  7,  8,  9],
        [ 0,  0, 12, 13, 14],
        [ 0,  0,  0, 18, 19]],
       [[20, 21, 22, 23, 24],
        [ 0, 26, 27, 28, 29],
        [ 0,  0, 32, 33, 34],
        [ 0,  0,  0, 38, 39]],
       [[40, 41, 42, 43, 44],
        [ 0, 46, 47, 48, 49],
        [ 0,  0, 52, 53, 54],
        [ 0,  0,  0, 58, 59]]])

4.6 numpy.vander

  • numpy.vander(x, N=None, increasing=False)
  • 生成范德蒙德矩阵。

Example1

x = np.array([1, 2, 3, 5])
np.vander(x, 3)
#输出结果
array([[ 1,  1,  1],
       [ 4,  2,  1],
       [ 9,  3,  1],
       [25,  5,  1]])

Example2

N = 3
np.column_stack([x**(N-1-i) for i in range(N)])
#输出结果
array([[ 1,  1,  1],
       [ 4,  2,  1],
       [ 9,  3,  1],
       [25,  5,  1]])

Example3

x = np.array([1, 2, 3, 5])
np.vander(x)
#输出结果
array([[  1,   1,   1,   1],
       [  8,   4,   2,   1],
       [ 27,   9,   3,   1],
       [125,  25,   5,   1]])

np.vander(x, increasing=True)
#输出结果
array([[  1,   1,   1,   1],
       [  1,   2,   4,   8],
       [  1,   3,   9,  27],
       [  1,   5,  25, 125]])

5 The Matrix class

MethodReturn
mat(data[, dtype]) 将输入解释为矩阵。
bmat(obj[, ldict, gdict]) 从字符串、嵌套序列或数组构建矩阵对象。

5.1 numpy.mat

  • numpy.mat(data, dtype=None)
  • 将输入解释为矩阵。

Examples

x = np.array([[1, 2], [3, 4]])
m = np.asmatrix(x)
x[0,0] = 5
m
#输出结果
matrix([[5, 2],
[3, 4]])

5.2 numpy.bmat

  • numpy.bmat(obj, ldict=None, gdict=None)
  • 从字符串、嵌套序列或数组构建矩阵对象。

Examples

A = np.mat('1 1; 1 1')
B = np.mat('2 2; 2 2')
C = np.mat('3 4; 5 6')
D = np.mat('7 8; 9 0')
np.bmat([[A, B], [C, D]])
#输出结果
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])

np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
#输出结果
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])

np.bmat('A,B; C,D')
#输出结果
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])

 

posted @ 2022-02-10 00:03  多发Paper哈  阅读(81)  评论(0编辑  收藏  举报
Live2D