高强度快速入门numpy,节选自官方manual

本文详细介绍了NumPy库的基础使用,包括数组创建、基本运算、通用函数、索引与切片等,并深入探讨了数组形状操作、复制与视图、广播规则及高级索引技巧,适合初学者快速上手并深入掌握。

起因

是我很长时间没有用python的numpy了,于是重新啃了啃原始官方manual。
版本:numpy v1.19
点击这里从官网下载:https://numpy.org/doc/1.19/numpy-user.pdf

import numpy as np

2.2.2 Array Creation

按照python列表创建

创建全0,全1的array

创建一个空的array

np.array( [ [1,2,3], [3,4,5] ])
array([[1, 2, 3],
       [3, 4, 5]])
np.zeros((3,4))
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])

此外还有zeros_like函数

np.ones( (2,3,4), dtype=np.int16 )
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]], dtype=int16)

此外还有ones_like函数

np.empty( (2,3) )
array([[0., 0., 0.],
       [0., 0., 0.]])

此外还有empty_like函数

创建一些列值的数组:

  • arange(开始值,结束值,步长),和python的ranage用法是一样的
  • linspace(开始值,结束值,划分数量)
np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
np.arange( 0, 2, 0.3 )
array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
np.linspace( 0, 2, 9 )
array([0.  , 0.25, 0.5 , 0.75, 1.  , 1.25, 1.5 , 1.75, 2.  ])
x = np.linspace( 0, 2*np.pi, 22 )    ##可以处理比较复杂的序列划分
f = np.sin(x)
print(f)
[ 0.00000000e+00  2.94755174e-01  5.63320058e-01  7.81831482e-01
  9.30873749e-01  9.97203797e-01  9.74927912e-01  8.66025404e-01
  6.80172738e-01  4.33883739e-01  1.49042266e-01 -1.49042266e-01
 -4.33883739e-01 -6.80172738e-01 -8.66025404e-01 -9.74927912e-01
 -9.97203797e-01 -9.30873749e-01 -7.81831482e-01 -5.63320058e-01
 -2.94755174e-01 -2.44929360e-16]

2.2.3 Printing Arrays

# np.set_printoptions(threshold=sys.maxsize)## 通过这个指令可以让输出的时候不再有很多省略,全部输出

2.2.4 Basic Operations

两个array的乘法:点乘和叉乘

A = np.array( [[1,1],[0,1]] )
B = np.array( [[2,0],[3,4]] )
A * B # elementwise product
array([[2, 0],
       [0, 4]])
A @ B # matrix product
array([[5, 4],
       [3, 4]])
A.dot(B) # another matrix product
array([[5, 4],
       [3, 4]])

有一些和数组无关的操作也会直接集成在ndarray类中

rg = np.random.default_rng(1)
a224 = rg.random((2,3))
print(a224)
print("sum: ",a224.sum())
print("min: ",a224.min())
print("max: ",a224.max())
[[0.51182162 0.9504637  0.14415961]
 [0.94864945 0.31183145 0.42332645]]
sum:  3.290252281866131
min:  0.14415961271963373
max:  0.9504636963259353

2.2.5 Universal Functions

包含了一些常见的操作与数学运算,比如exp, sqrt, add, all, any, apply_along_axis, argmax, argmin, argsort, average, bincount, ceil, clip, conj,
corrcoef, cov, cross, cumprod, cumsum, diff, dot, floor, inner, invert, lexsort, max, maximum,
mean, median, min, minimum, nonzero, outer, prod, re, round, sort, std, sum, trace, transpose,
var, vdot, vectorize, where 等等

2.2.6 Indexing, Slicing and Iterating

一维的数组可以被索引,划分和迭代。和python中的列表差不多

a = np.arange(10)**3
print(a)
a[::-1]    ##列表翻转小技巧
[  0   1   8  27  64 125 216 343 512 729]





array([729, 512, 343, 216, 125,  64,  27,   8,   1,   0], dtype=int32)

多维数组每一个axis有一个index,是一个用逗号分隔的元组

b = np.fromfunction(lambda x,y:10*x+y,(5,4), dtype=int)
b
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])
b[2,3]
23
b[0:5, 1]     # each row in the second column of b
array([ 1, 11, 21, 31, 41])
b[ : ,1] # equivalent to the previous example
array([ 1, 11, 21, 31, 41])
b[1:3, : ] # each column in the second and third row of b
array([[10, 11, 12, 13],
       [20, 21, 22, 23]])

当拥有小于维度的参数时,后面默认为:

b[-1] # the last row. Equivalent to b[-1,:]
array([40, 41, 42, 43])

“…”这样的表示方式是有尽可能多的列,也就是尽可能多的“:”

The dots (…) represent as many colons as needed to produce a complete indexing tuple

  • x[1,2,…] is equivalent to x[1,2,:,:,:]
  • x[…,3] to x[:,:,:,:,3] and
  • x[4,…,5,:] to x[4,:,:,5,:].
c = np.array( [[[ 0, 1, 2], [ 10, 12, 13]],[[100,101,102],[110,112,113]]])
print(c.shape)
print(c[1,...])
print(c[...,2])
(2, 2, 3)
[[100 101 102]
 [110 112 113]]
[[  2  13]
 [102 113]]

如果需要挨个打印元素的话,可以使用flat属性

for elem in c.flat:
    print(elem)
0
1
2
10
12
13
100
101
102
110
112
113

2.3 Shape Manipulation

2.3.1 Changing the shape of an array

a = np.floor(10*rg.random((3,4)))
print(a)
print("shape: ",str(a.shape))
[[8. 4. 5. 0.]
 [7. 5. 3. 7.]
 [3. 4. 1. 4.]]
shape:  (3, 4)

下面的三个指令返回一个修改过的array,但是不会修改原array

  • ravel()
  • reshape()
  • T
a.ravel() # returns the array, flattened
array([8., 4., 5., 0., 7., 5., 3., 7., 3., 4., 1., 4.])
a.reshape(6,2) # returns the array with a modified shape
array([[8., 4.],
       [5., 0.],
       [7., 5.],
       [3., 7.],
       [3., 4.],
       [1., 4.]])
a.T # returns the array, transposed
array([[8., 7., 3.],
       [4., 5., 4.],
       [5., 3., 1.],
       [0., 7., 4.]])
a.T.shape
(4, 3)
a.shape  #并没有修改原始数据
(3, 4)

reshape函数会创建一个array的副本,而resize函数会改变array内容本身

如果维度参数是-1,那么这个参数就会被自动计算

print(a)
a.resize((2,6))
print(a)
[[8. 4. 5. 0.]
 [7. 5. 3. 7.]
 [3. 4. 1. 4.]]
[[8. 4. 5. 0. 7. 5.]
 [3. 7. 3. 4. 1. 4.]]
a = a.reshape(3,-1)
print(a)
[[8. 4. 5. 0.]
 [7. 5. 3. 7.]
 [3. 4. 1. 4.]]

2.3.2 Stacking together different arrays

a = np.floor(10*rg.random((2,2)))
print("a: ",a)
b = np.floor(10*rg.random((2,2)))
print("b: ",b)
print("vstack: ",np.vstack((a,b)))
print("hstack: ",np.hstack((a,b)))
a:  [[5. 2.]
 [1. 9.]]
b:  [[5. 1.]
 [6. 7.]]
vstack:  [[5. 2.]
 [1. 9.]
 [5. 1.]
 [6. 7.]]
hstack:  [[5. 2. 5. 1.]
 [1. 9. 6. 7.]]

函数column_stack将一维的数组作为column叠到二维数组中,此外还有row_stack操作

from numpy import newaxis
np.column_stack((a,b))
array([[5., 2., 5., 1.],
       [1., 9., 6., 7.]])
a = np.array([4.,2.])
b = np.array([3.,8.])
print(np.column_stack((a,b))) # returns a 2D array
print(np.hstack((a,b)))  # the result is different
[[4. 3.]
 [2. 8.]]
[4. 2. 3. 8.]
print(a[:,newaxis])  # view `a` as a 2D column vector
print(np.column_stack((a[:,newaxis],b[:,newaxis])))
print(np.hstack((a[:,newaxis],b[:,newaxis])))  # the result is the same
[[4.]
 [2.]]
[[4. 3.]
 [2. 8.]]
[[4. 3.]
 [2. 8.]]

2.3.3 Splitting one array into several smaller ones

a = np.floor(10*rg.random((2,12)))
a
array([[6., 9., 0., 5., 4., 0., 6., 8., 5., 2., 8., 5.],
       [5., 7., 1., 8., 6., 7., 1., 8., 1., 0., 8., 8.]])
np.hsplit(a,3)   #Split a into 3
[array([[6., 9., 0., 5.],
        [5., 7., 1., 8.]]),
 array([[4., 0., 6., 8.],
        [6., 7., 1., 8.]]),
 array([[5., 2., 8., 5.],
        [1., 0., 8., 8.]])]
np.hsplit(a,(3,4))  # Split a after the third and the fourth column
[array([[6., 9., 0.],
        [5., 7., 1.]]),
 array([[5.],
        [8.]]),
 array([[4., 0., 6., 8., 5., 2., 8., 5.],
        [6., 7., 1., 8., 1., 0., 8., 8.]])]

2.4 Copies and Views

2.4.1 No Copy at All

b=a

2.4.2 View or Shallow Copy

c = a.view()

2.4.3 Deep Copy

d = a.copy()

2.4.4 Functions and Methods Overview

Array Creation

  • arange, array, copy, empty, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones, ones_like, r_, zeros, zeros_like

Conversions

  • ndarray.astype, atleast_1d, atleast_2d, atleast_3d, mat Manipulations
    array_split, column_stack, concatenate, diagonal, dsplit, dstack, hsplit, hstack, ndarray.item, newaxis, ravel, repeat, reshape, resize, squeeze, swapaxes, take, transpose, vsplit, vstack

Questions

  • all, any, nonzero, where

Ordering

  • argmax, argmin, argsort, max, min, ptp, searchsorted, sort

Operations

  • choose, compress, cumprod, cumsum, inner, ndarray.fill, imag, prod, put, putmask, real,sum

Basic Statistics

  • cov, mean, std, var

Basic Linear Algebra

  • cross, dot, outer, linalg.svd, vdot

2.5 Less Basic(一些高级内容:广播)

2.5.1 Broadcasting rules

2.6 Advanced indexing and index tricks

2.6.1 Indexing with Arrays of Indices

a = np.arange(12)**2 # the first 12 square numbers
i = np.array([1, 1, 3, 8, 5]) # an array of indices
a[i] # the elements of a at the positions i
array([ 1,  1,  9, 64, 25], dtype=int32)
j = np.array([[3, 4], [9, 7]]) # a bidimensional array of indices
a[j] # the same shape as j
array([[ 9, 16],
       [81, 49]], dtype=int32)
palette = np.array([[0, 0, 0], # black
    [255, 0, 0],               # red
    [0, 255, 0],               # green
    [0, 0, 255],               # blue
    [255, 255, 255]])          # white
image = np.array([[0, 1, 2, 0], # each value corresponds to a color in the palette
                [0, 3, 4, 0]])
palette[image] # the (2, 4, 3) color image
array([[[  0,   0,   0],
        [255,   0,   0],
        [  0, 255,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0, 255],
        [255, 255, 255],
        [  0,   0,   0]]])

后面还有一些高级的索引方式和元素操作,我看不懂就不写了

2.7 Linear Algebra:

numpy.linalg 模块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值