Numpy 数组和矢量计算
代码下载
import numpy as np
创建ndarray
data1=[6,7.5,8,0,1]
arr1=np.array(data1)
arr1
array([ 6. , 7.5, 8. , 0. , 1. ])
data2=[[1,2,3,4],[5,6,7,8]]
arr2=np.array(data2)
arr2
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
arr2.ndim
2
arr2.shape
(2, 4)
arr1.dtype
dtype('float64')
arr2.dtype
dtype('int32')
np.zeros(10)
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
np.zeros((3,6))
array([[ 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0.]])
np.empty((2,3,2))
array([[[ 1.37556714e-311, 0.00000000e+000],
[ 0.00000000e+000, 0.00000000e+000],
[ 0.00000000e+000, 0.00000000e+000]],
[[ 0.00000000e+000, 0.00000000e+000],
[ 0.00000000e+000, 0.00000000e+000],
[ 0.00000000e+000, 0.00000000e+000]]])
np.arange(15)
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
arr3=np.array([1,2,3],dtype=np.float64)
arr4=np.array([1,2,3],dtype=np.int32)
arr3.dtype
dtype('float64')
arr4.dtype
dtype('int32')
arr5=np.array([1,2,3,4,5])
arr5.dtype
dtype('int32')
float_arr5=arr5.astype(np.float64)
float_arr5.dtype
dtype('float64')
arr6=np.array([3.7,1.2,3.5,6.4,-0.5,0.9])
arr6
array([ 3.7, 1.2, 3.5, 6.4, -0.5, 0.9])
arr6.astype(np.int32)
array([3, 1, 3, 6, 0, 0])
numeric_strings=np.array(['1.25','3.44','5.64'],dtype=np.string_)
numeric_strings.astype(float)
array([ 1.25, 3.44, 5.64])
int_array=np.arange(10)
calibers=np.array([.22,.270,.357,.380,.44,.50],dtype=np.float64)
int_array.astype(calibers.dtype)
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
empty_uint32=np.empty(8,dtype='u4')
empty_uint32
array([0, 0, 1, 0, 2, 0, 3, 0], dtype=uint32)
数组和标量之间的运算
arr=np.array([[1.,2.,3.],[4.,5.,6.]])
arr
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
arr*arr
array([[ 1., 4., 9.],
[ 16., 25., 36.]])
1/arr
array([[ 1. , 0.5 , 0.33333333],
[ 0.25 , 0.2 , 0.16666667]])
arr*0.5
array([[ 0.5, 1. , 1.5],
[ 2. , 2.5, 3. ]])
基本的索引和切片
arr=np.arange(10)
arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[5]
5
arr[5:8]
array([5, 6, 7])
arr[5:8]=12
arr
array([ 0, 1, 2, 3, 4, 12, 12, 12, 8, 9])
arr_slice=arr[5:8]
arr_slice[1]=12345
arr
array([ 0, 1, 2, 3, 4, 12, 12345, 12, 8, 9])
arr_slice[:]=64
arr
array([ 0, 1, 2, 3, 4, 64, 64, 64, 8, 9])
arr2d=np.array([[1,2,3],[4,5,6],[7,8,9]])
arr2d[2]
array([7, 8, 9])
arr2d[0][2]
3
arr2d[0,2]
3
arr3d=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
arr3d
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
arr3d[0]
array([[1, 2, 3],
[4, 5, 6]])
old_values=arr3d[0].copy()
arr3d[0]=42
arr3d
array([[[42, 42, 42],
[42, 42, 42]],
[[ 7, 8, 9],
[10, 11, 12]]])
arr3d[0]=old_values
arr3d
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
arr3d[1,0]
array([7, 8, 9])
arr[1:6]
array([ 1, 2, 3, 4, 64])
arr2d
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
arr2d[:2]
array([[1, 2, 3],
[4, 5, 6]])
arr2d[:2,1:]
array([[2, 3],
[5, 6]])
arr2d[1,:2]
array([4, 5])
arr2d[2,:1]
array([7])
arr2d[:,:1]
array([[1],
[4],
[7]])
布尔型索引
names=np.array(['Bob','Joe','Will','Bob','Will','Joe','Joe'])
data=np.random.randn(7,4)
names
array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'],
dtype='<U4')
data
array([[ 1.60975139e-03, -3.23542576e-01, 1.76647590e+00,
1.00434873e-01],
[ -1.00265678e+00, -2.06101922e-01, -1.98938974e+00,
1.03029242e-01],
[ -4.59143820e-01, 6.32877040e-01, 6.65959171e-02,
-9.06221248e-01],
[ 1.69835755e-01, -3.53395803e-01, 1.05681390e+00,
-4.89362964e-01],
[ -1.63716077e+00, 3.09182690e+00, -2.81776081e-01,
6.14541313e-01],
[ 8.23892259e-01, -6.11722686e-01, 6.27307169e-01,
-3.55724014e-02],
[ 1.71960690e+00, 2.35358233e-01, -1.58146445e+00,
1.11900395e+00]])
names=='Bob'
array([ True, False, False, True, False, False, False], dtype=bool)
data[names=='Bob']
array([[ 1.60975139e-03, -3.23542576e-01, 1.76647590e+00,
1.00434873e-01],
[ 1.69835755e-01, -3.53395803e-01, 1.05681390e+00,
-4.89362964e-01]])
data[names=='Bob',2:]
array([[ 1.7664759 , 0.10043487],
[ 1.0568139 , -0.48936296]])
data[names=='Bob',3]
array([ 0.10043487, -0.48936296])
names!='Bob'
array([False, True, True, False, True, True, True], dtype=bool)
data[~(names=='Bob')]
array([[-1.00265678, -0.20610192, -1.98938974, 0.10302924],
[-0.45914382, 0.63287704, 0.06659592, -0.90622125],
[-1.63716077, 3.0918269 , -0.28177608, 0.61454131],
[ 0.82389226, -0.61172269, 0.62730717, -0.0355724 ],
[ 1.7196069 , 0.23535823, -1.58146445, 1.11900395]])
mask=(names=='Bob')|(names=='Will')
mask
array([ True, False, True, True, True, False, False], dtype=bool)
data[mask]
array([[ 1.60975139e-03, -3.23542576e-01, 1.76647590e+00,
1.00434873e-01],
[ -4.59143820e-01, 6.32877040e-01, 6.65959171e-02,
-9.06221248e-01],
[ 1.69835755e-01, -3.53395803e-01, 1.05681390e+00,
-4.89362964e-01],
[ -1.63716077e+00, 3.09182690e+00, -2.81776081e-01,
6.14541313e-01]])
data[data<0]=0
data
array([[ 1.60975139e-03, 0.00000000e+00, 1.76647590e+00,
1.00434873e-01],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.03029242e-01],
[ 0.00000000e+00, 6.32877040e-01, 6.65959171e-02,
0.00000000e+00],
[ 1.69835755e-01, 0.00000000e+00, 1.05681390e+00,
0.00000000e+00],
[ 0.00000000e+00, 3.09182690e+00, 0.00000000e+00,
6.14541313e-01],
[ 8.23892259e-01, 0.00000000e+00, 6.27307169e-01,
0.00000000e+00],
[ 1.71960690e+00, 2.35358233e-01, 0.00000000e+00,
1.11900395e+00]])
data[names!='Joe']=7
data
array([[ 7. , 7. , 7. , 7. ],
[ 0. , 0. , 0. , 0.10302924],
[ 7. , 7. , 7. , 7. ],
[ 7. , 7. , 7. , 7. ],
[ 7. , 7. , 7. , 7. ],
[ 0.82389226, 0. , 0.62730717, 0. ],
[ 1.7196069 , 0.23535823, 0. , 1.11900395]])
花式索引
指的是利用整数数组进行索引。
arr=np.empty((8,4))
for i in range(8):
arr[i]=i
arr
array([[ 0., 0., 0., 0.],
[ 1., 1., 1., 1.],
[ 2., 2., 2., 2.],
[ 3., 3., 3., 3.],
[ 4., 4., 4., 4.],
[ 5., 5., 5., 5.],
[ 6., 6., 6., 6.],
[ 7., 7., 7., 7.]])
arr[[4,3,0,6]]
array([[ 4., 4., 4., 4.],
[ 3., 3., 3., 3.],
[ 0., 0., 0., 0.],
[ 6., 6., 6., 6.]])
arr[[-3,-5,-7]]
array([[ 5., 5., 5., 5.],
[ 3., 3., 3., 3.],
[ 1., 1., 1., 1.]])
arr=np.arange(32).reshape((8,4))
arr
array([[ 0, 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]])
arr[[1,5,7,2],[0,3,1,2]]
array([ 4, 23, 29, 10])
arr[[1,5,7,2]][:,[0,3,1,2]]
array([[ 4, 7, 5, 6],
[20, 23, 21, 22],
[28, 31, 29, 30],
[ 8, 11, 9, 10]])
arr[np.ix_([1,5,7,2],[0,3,1,2])]
array([[ 4, 7, 5, 6],
[20, 23, 21, 22],
[28, 31, 29, 30],
[ 8, 11, 9, 10]])
记住,花式索引跟切片不一样,它总是将数据复制到新数组中。
数组转置和轴对称
转置(transpose)是重塑的一种特殊形式,它返回的是源数据的视图(不会进行任何复制操作)。
arr=np.arange(15).reshape((3,5))
arr
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
arr.T
array([[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]])
arr=np.random.randn(6,3)
np.dot(arr.T,arr)
array([[ 8.84595216, 2.30542093, 3.92854057],
[ 2.30542093, 2.28401128, 1.73860755],
[ 3.92854057, 1.73860755, 9.77924613]])
arr=np.arange(16).reshape((2,2,4))
arr
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
arr.transpose((1,0,2))
array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],
[[ 4, 5, 6, 7],
[12, 13, 14, 15]]])
arr
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
arr.swapaxes(1,2)
array([[[ 0, 4],
[ 1, 5],
[ 2, 6],
[ 3, 7]],
[[ 8, 12],
[ 9, 13],
[10, 14],
[11, 15]]])
通用函数:快速的元素级数据函数
arr=np.arange(10)
np.sqrt(arr)
array([ 0. , 1. , 1.41421356, 1.73205081, 2. ,
2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ])
np.exp(arr)
array([ 1.00000000e+00, 2.71828183e+00, 7.38905610e+00,
2.00855369e+01, 5.45981500e+01, 1.48413159e+02,
4.03428793e+02, 1.09663316e+03, 2.98095799e+03,
8.10308393e+03])
x=np.random.randn(8)
y=np.random.randn(8)
x
array([-1.55455343, 0.58957206, 1.12291564, 0.84985964, 1.81809564,
0.96211051, 0.03536402, -0.29113791])
y
array([ 1.35585258, -0.18208383, -0.96881932, -0.97084842, 0.15031288,
-0.21753205, -0.12555617, 1.07649061])
np.maximum(x,y)
array([ 1.35585258, 0.58957206, 1.12291564, 0.84985964, 1.81809564,
0.96211051, 0.03536402, 1.07649061])
arr=np.random.randn(7)*5
np.modf(arr)
(array([-0.99321578, 0.62223866, 0.32422504, -0.20182624, -0.74306072,
-0.10960894, 0.95203083]), array([-2., 2., 2., -4., -1., -6., 5.]))
np.fabs(arr)
array([ 2.99321578, 2.62223866, 2.32422504, 4.20182624, 1.74306072,
6.10960894, 5.95203083])
利用数组进行数据处理
points=np.arange(-5,5,0.01)
xs,ys=np.meshgrid(points,points)
ys
array([[-5. , -5. , -5. , ..., -5. , -5. , -5. ],
[-4.99, -4.99, -4.99, ..., -4.99, -4.99, -4.99],
[-4.98, -4.98, -4.98, ..., -4.98, -4.98, -4.98],
...,
[ 4.97, 4.97, 4.97, ..., 4.97, 4.97, 4.97],
[ 4.98, 4.98, 4.98, ..., 4.98, 4.98, 4.98],
[ 4.99, 4.99, 4.99, ..., 4.99, 4.99, 4.99]])
import matplotlib.pyplot as plt
z=np.sqrt(xs**2+ys**2)
z
array([[ 7.07106781, 7.06400028, 7.05693985, ..., 7.04988652,
7.05693985, 7.06400028],
[ 7.06400028, 7.05692568, 7.04985815, ..., 7.04279774,
7.04985815, 7.05692568],
[ 7.05693985, 7.04985815, 7.04278354, ..., 7.03571603,
7.04278354, 7.04985815],
...,
[ 7.04988652, 7.04279774, 7.03571603, ..., 7.0286414 ,
7.03571603, 7.04279774],
[ 7.05693985, 7.04985815, 7.04278354, ..., 7.03571603,
7.04278354, 7.04985815],
[ 7.06400028, 7.05692568, 7.04985815, ..., 7.04279774,
7.04985815, 7.05692568]])
plt.imshow(z,cmap=plt.cm.gray)
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x28840dd65c0>
plt.title('Image plot of $\sqrt(x^2+y^2)$ for a grid of values')
<matplotlib.text.Text at 0x28841041dd8>
将条件逻辑表述为数组运算
xarr=np.array([1.1,1.2,1.3,1.4,1.5])
yarr=np.array([2.1,2.2,2.3,2.4,2.5])
cond=np.array([True,False,True,True,False])
result=[(x if c else y) for x,y,c in zip(xarr,yarr,cond)]
result
[1.1000000000000001, 2.2000000000000002, 1.3, 1.3999999999999999, 2.5]
result=np.where(cond,xarr,yarr)
result
array([ 1.1, 2.2, 1.3, 1.4, 2.5])
arr=np.random.randn(4,4)
arr
array([[-1.124892 , 0.16102557, -0.84624401, -1.61350592],
[ 0.93525737, -1.97957635, -2.53954932, 0.79295019],
[-1.40451591, 0.31596234, -1.43060903, -1.61587221],
[-1.00342438, 0.88479574, 1.52961242, 0.72461918]])
np.where(arr>0,2,-2)
array([[-2, 2, -2, -2],
[ 2, -2, -2, 2],
[-2, 2, -2, -2],
[-2, 2, 2, 2]])
np.where(arr>0,2,arr)
array([[-1.124892 , 2. , -0.84624401, -1.61350592],
[ 2. , -1.97957635, -2.53954932, 2. ],
[-1.40451591, 2. , -1.43060903, -1.61587221],
[-1.00342438, 2. , 2. , 2. ]])
数学和统计方法
arr=np.random.randn(5,4)
arr.mean()
0.22588105368397526
np.mean(arr)
0.22588105368397526
arr.sum()
4.5176210736795053
arr.mean(axis=1)
array([ 0.67230987, 0.01274547, 0.18780888, 0.54016805, -0.283627 ])
arr.sum(0)
array([ 0.06725924, 0.51484031, 1.7496478 , 2.18587372])
arr=np.array([[0,1,2],[3,4,5],[6,7,8]])
arr
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
arr.cumsum(0)
array([[ 0, 1, 2],
[ 3, 5, 7],
[ 9, 12, 15]], dtype=int32)
arr.cumprod(1)
array([[ 0, 0, 0],
[ 3, 12, 60],
[ 6, 42, 336]], dtype=int32)
用于布尔型数组的方法
arr=np.random.randn(100)
(arr>0).sum()
49
bools=np.array([False,False,True,False])
bools.any()
True
bools.all()
False
排序
arr=np.random.randn(8)
arr
array([ 0.19051791, -0.9561823 , -0.88527884, 1.72500065, 0.7121868 ,
-0.98016434, -0.62017177, 1.56115109])
arr.sort()
arr
array([-0.98016434, -0.9561823 , -0.88527884, -0.62017177, 0.19051791,
0.7121868 , 1.56115109, 1.72500065])
arr=np.random.randn(5,3)
arr
array([[ 2.18671772, -0.52656283, 0.9128075 ],
[-0.60204952, 0.71479588, -0.03902287],
[-0.63784626, -1.89380845, -0.28438434],
[ 1.22924442, 0.16689474, -0.63089802],
[ 0.72705863, 2.18074376, 0.47051067]])
arr.sort(1)
arr
array([[-0.52656283, 0.9128075 , 2.18671772],
[-0.60204952, -0.03902287, 0.71479588],
[-1.89380845, -0.63784626, -0.28438434],
[-0.63089802, 0.16689474, 1.22924442],
[ 0.47051067, 0.72705863, 2.18074376]])
唯一化以及其他的集合逻辑
names=np.array(['Bob','Joe','Will','Bob','Will','Joe','Joe'])
np.unique(names)
array(['Bob', 'Joe', 'Will'],
dtype='<U4')
ints=np.array([3,3,4,2,1,3,2,4])
np.unique(ints)
array([1, 2, 3, 4])
sorted(set(names))
['Bob', 'Joe', 'Will']
values=np.array([6,0,0,3,2,5,6])
np.in1d(values,[2,3,6])
array([ True, False, False, True, True, False, True], dtype=bool)
用于数组的文件输入输出
arr=np.arange(10)
np.save('ch04/some_array',arr)
np.load('ch04/some_array.npy')
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.savez('ch04/array_archive.npz',a=arr,b=arr)
arch=np.load('ch04/array_archive.npz')
arch['b']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
存取文本文件
arr=np.loadtxt('ch04/array_ex.txt',delimiter=',')
arr
array([[ 0.580052, 0.18673 , 1.040717, 1.134411],
[ 0.194163, -0.636917, -0.938659, 0.124094],
[-0.12641 , 0.268607, -0.695724, 0.047428],
[-1.484413, 0.004176, -0.744203, 0.005487],
[ 2.302869, 0.200131, 1.670238, -1.88109 ],
[-0.19323 , 1.047233, 0.482803, 0.960334]])
np.savetxt('ch04/array_txt.txt',arr,delimiter=' ',newline='\n')
线性代数
x=np.array([[1.,2.,3.],[4.,5.,6.]])
y=np.array([[6.,23.],[-1,7],[8,9]])
x
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
y
array([[ 6., 23.],
[ -1., 7.],
[ 8., 9.]])
x.dot(y)
array([[ 28., 64.],
[ 67., 181.]])
np.dot(x,np.ones(3))
array([ 6., 15.])
from numpy.linalg import inv,qr
X=np.random.randn(5,5)
mat=X.T.dot(X)
mat
array([[ 3.52812683, 0.50014532, -1.33983697, 1.65988419, -0.76535951],
[ 0.50014532, 4.08419311, -2.5690617 , -0.16615284, -3.74006228],
[-1.33983697, -2.5690617 , 2.72421214, -0.13432057, 4.16986366],
[ 1.65988419, -0.16615284, -0.13432057, 3.2039997 , -0.87473058],
[-0.76535951, -3.74006228, 4.16986366, -0.87473058, 8.06038483]])
inv(mat)
array([[ 54.04030339, 25.14468473, 138.84119709, -36.99114311,
-59.04224289],
[ 25.14468473, 12.31566469, 65.26559276, -17.16636841,
-27.52455358],
[ 138.84119709, 65.26559276, 359.29868506, -95.18079197,
-152.73752953],
[ -36.99114311, -17.16636841, -95.18079197, 25.66540608,
40.54724899],
[ -59.04224289, -27.52455358, -152.73752953, 40.54724899,
65.1619639 ]])
mat.dot(inv(mat))
array([[ 1.00000000e+00, -1.42108547e-14, -2.84217094e-14,
1.42108547e-14, -1.42108547e-14],
[ -2.84217094e-14, 1.00000000e+00, 1.13686838e-13,
-5.68434189e-14, -8.52651283e-14],
[ 2.84217094e-14, 0.00000000e+00, 1.00000000e+00,
0.00000000e+00, 5.68434189e-14],
[ -7.10542736e-15, -7.10542736e-15, -5.68434189e-14,
1.00000000e+00, -7.10542736e-15],
[ 1.13686838e-13, 2.84217094e-14, 0.00000000e+00,
-5.68434189e-14, 1.00000000e+00]])
q,r=qr(mat)
r
array([[ -4.22302950e+00, -2.32915443e+00, 3.09645494e+00,
-2.82756748e+00, 4.20997326e+00],
[ 0.00000000e+00, -5.66758935e+00, 4.67966804e+00,
5.91077981e-01, 8.21617203e+00],
[ 0.00000000e+00, 0.00000000e+00, -1.31721365e+00,
1.90947603e-01, -3.21644932e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
-2.33466484e+00, 1.45658073e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 5.46664408e-03]])
随机数生成
samples=np.random.randn(4,4)
samples
array([[ 1.5404748 , -0.92115435, 1.00509721, 0.43422671],
[ 0.69277073, 0.18068919, 0.60346547, -0.35861855],
[ 1.05033574, 1.16613186, -1.0336046 , -0.71084958],
[-0.06515771, 1.3693006 , 1.40907517, -0.94190917]])
nsteps=1000
draws=np.random.randint(0,2,size=nsteps)
steps=np.where(draws>0,1,-1)
walk=steps.cumsum()
walk.min()
-25
walk.max()
7
(np.abs(walk)>=10).argmax()
65
nwalks=5000
nsteps=1000
draws=np.random.randint(0,2,size=(nwalks,nsteps))
steps=np.where(draws>0,1,-1)
walks=steps.cumsum(1)
walks
array([[ 1, 2, 3, ..., -28, -29, -30],
[ -1, 0, 1, ..., 10, 11, 12],
[ 1, 2, 3, ..., 46, 47, 48],
...,
[ -1, -2, -3, ..., 0, 1, 0],
[ -1, 0, 1, ..., -8, -7, -8],
[ 1, 2, 3, ..., 44, 43, 42]], dtype=int32)
walks.max()
146
walks.min()
-114
hits30=(np.abs(walks)>=30).any(1)
hits30
array([ True, False, True, ..., False, True, True], dtype=bool)
hits30.sum()
3417
crossing_times=(np.abs(walks[hits30])>=30).argmax(1)
crossing_times.mean()
500.91747146619844