python-numpy数组

NumPy Basics: Arrays and
# 优点:
# NumPy是在⼀个连续的内存块中存储数据,独⽴于其他
# Python内置对象。
# NumPy可以在整个数组上执⾏复杂的计算,
import numpy as np
np.random.seed(12345)
import matplotlib.pyplot as plt
plt.rc('figure', figsize=(10, 6))
np.set_printoptions(precision=4, suppress=True)
import numpy as np
my_arr = np.arange(1000000)
my_list = list(range(1000000))
# 查看语句性能
%time for _ in range(10): my_arr2 = my_arr * 2
%time for _ in range(10): my_list2 = [x * 2 for x in my_list]
Wall time: 40.9 ms
Wall time: 1.39 s
The NumPy ndarray: A Multidimensional Array Object
使⽤标准的NumPy惯⽤
# 法import numpy as np。你当然也可以在代码中使
# ⽤from numpy import *,但不建议这么做。numpy的命名空
# 间很⼤,包含许多函数
# 4.1 NumPy的ndarray:⼀种多维数组对象
# ⽣成⼀个包含随机数据的⼩数组:
# 使⽤标准的NumPy惯⽤
# 法import numpy as np。你当然也可以在代码中使
# ⽤from numpy import *,但不建议这么做。numpy的命名空
# 间很⼤,包含许多函数
import numpy as np
# Generate some random data
data = np.random.randn(2, 3)
data
array([[ 0.0929, 0.2817, 0.769 ],
[ 1.2464, 1.0072, -1.2962]])
# 进⾏数学运算
data * 10
data + data
array([[ 0.1858, 0.5635, 1.538 ],
[ 2.4929, 2.0144, -2.5924]])
data.shape
data.dtype
dtype('float64')
Creating ndarrays
# 创建NumPy数组
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
arr2.shape
(2, 4)
arr1.dtype
arr2.dtype
dtype('int32')
# zeros和ones
np.zeros(10)
np.zeros((3, 6))
np.empty((2, 3, 2))
array([[[8.4766e-312, 3.1620e-322],
[0.0000e+000, 0.0000e+000],
[0.0000e+000, 4.2806e-037]],

[[3.8853e-057, 2.2139e-052],
[1.3929e+165, 4.2771e-033],
[7.8692e-071, 1.2215e+165]]])
np.arange(15)
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
Data Types for ndarrays
设置数值类型
# 创建数组,设置数值类型
arr1 = np.array([1, 2, 3], dtype=np.float64)
arr2 = np.array([1, 2, 3], dtype=np.int32)
arr1.dtype
arr2.dtype
dtype('int32')
# 转换类型 将⼀个数组从⼀个dtype转换成另⼀个dtype
arr = np.array([1, 2, 3, 4, 5])
arr.dtype
float_arr = arr.astype(np.float64)
float_arr.dtype
dtype('float64')
arr = np.array([3.7, -1.2, -2.6, 0.5, 12.9, 10.1])
arr
arr.astype(np.int32)
array([ 3, -1, -2, 0, 12, 10])
numeric_strings = np.array(['1.25', '-9.6', '42'], dtype=np.string_)
numeric_strings.astype(float)
array([ 1.25, -9.6 , 42. ])
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, 1075314688, 0, 1075707904, 0,
1075838976, 0, 1072693248], dtype=uint32)

数组计算 切片索引

Arithmetic with NumPy Arrays¶
# NumPy数组的运算
arr = np.array([[1., 2., 3.], [4., 5., 6.]])
arr
arr * arr
arr - arr
array([[0., 0., 0.],
[0., 0., 0.]])
1 / arr
arr ** 0.5
arr2 = np.array([[0., 4., 1.], [7., 2., 12.]])
arr2
arr2 > arr
Basic Indexing and Slicing
# 基本的索引和切⽚
arr = np.arange(10)
arr
arr[5]
arr[5:8]
arr[5:8] = 12
arr
arr_slice = arr[5:8]
arr_slice
arr_slice[1] = 12345
arr
# 切⽚[ : ]会给数组中的所有值赋值:
arr_slice[:] = 64
arr
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr2d[2]
array([7, 8, 9])
arr2d[0][2]
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
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])
x = arr3d[1]
x
x[0]
array([7, 8, 9])
Indexing with slices
# 切⽚索引
arr
arr[1:6]
array([[4., 5., 6.]])
arr2d
arr2d[:2]
arr2d[:2, 1:]
array([[2, 3],
[5, 6]])
arr2d[1, :2]
array([4, 5])
arr2d[:2, 2]
array([3, 6])
arr2d[:, :1]
array([[1],
[4],
[7]])
arr2d[:2, 1:] = 0
arr2d
array([[1, 0, 0],
[4, 0, 0],
[7, 8, 9]])
Boolean Indexing
# 布尔型索引
# numpy.random中的randn函数⽣成⼀些正态分布的随机数据:
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
data = np.random.randn(7, 4)
names
data
array([[ 0.275 , 0.2289, 1.3529, 0.8864],
[-2.0016, -0.3718, 1.669 , -0.4386],
[-0.5397, 0.477 , 3.2489, -1.0212],
[-0.5771, 0.1241, 0.3026, 0.5238],
[ 0.0009, 1.3438, -0.7135, -0.8312],
[-2.3702, -1.8608, -0.8608, 0.5601],
[-1.2659, 0.1198, -1.0635, 0.3329]])
names == 'Bob'
data[names == 'Bob']
data[names == 'Bob', 2:]
data[names == 'Bob', 3]
names != 'Bob'
data[~(names == 'Bob')]
cond = names == 'Bob'
data[~cond]
mask = (names == 'Bob') | (names == 'Will')
mask
data[mask]
data[data < 0] = 0
data
array([[0.275 , 0.2289, 1.3529, 0.8864],
[0. , 0. , 1.669 , 0. ],
[0. , 0.477 , 3.2489, 0. ],
[0. , 0.1241, 0.3026, 0.5238],
[0.0009, 1.3438, 0. , 0. ],
[0. , 0. , 0. , 0.5601],
[0. , 0.1198, 0. , 0.3329]])
data[names != 'Joe'] = 7
data
array([[7. , 7. , 7. , 7. ],
[0. , 0. , 1.669 , 0. ],
[7. , 7. , 7. , 7. ],
[7. , 7. , 7. , 7. ],
[7. , 7. , 7. , 7. ],
[0. , 0. , 0. , 0.5601],
[0. , 0.1198, 0. , 0.3329]])
Fancy Indexing
花式索引
# 花式索引(Fancy indexing)是⼀个NumPy术语,它指的是利⽤
# 整数数组进⾏索引。假设我们有⼀个8×4数组:
# 花式索引
# 花式索引(Fancy indexing)是⼀个NumPy术语,它指的是利⽤
# 整数数组进⾏索引。假设我们有⼀个8×4数组:
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
arr[[1, 5, 7, 2], [0, 3, 1, 2]]
arr[[1, 5, 7, 2]][:, [0, 3, 1, 2]]
Transposing Arrays and Swapping Axes
arr = np.arange(15).reshape((3, 5))
arr
arr.T
arr = np.random.randn(6, 3)
arr
np.dot(arr.T, arr)
arr = np.arange(16).reshape((2, 2, 4))
arr
arr.transpose((1, 0, 2))
arr
arr.swapaxes(1, 2)
Universal Functions: Fast Element-Wise Array Functions
arr = np.arange(10)
arr
np.sqrt(arr)
np.exp(arr)
x = np.random.randn(8)
y = np.random.randn(8)
x
y
np.maximum(x, y)
arr = np.random.randn(7) * 5
arr
remainder, whole_part = np.modf(arr)
remainder
whole_part
arr
np.sqrt(arr)
np.sqrt(arr, arr)
arr
arr
np.sqrt(arr)
np.sqrt(arr, arr)
Array-Oriented Programming with Arrays
# 4.3 利⽤数组进⾏数据处理
points = np.arange(-5, 5, 0.01) # 1000 equally spaced points
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]])
z = np.sqrt(xs ** 2 + ys ** 2)
z
array([[7.0711, 7.064 , 7.0569, ..., 7.0499, 7.0569, 7.064 ],
[7.064 , 7.0569, 7.0499, ..., 7.0428, 7.0499, 7.0569],
[7.0569, 7.0499, 7.0428, ..., 7.0357, 7.0428, 7.0499],
...,
[7.0499, 7.0428, 7.0357, ..., 7.0286, 7.0357, 7.0428],
[7.0569, 7.0499, 7.0428, ..., 7.0357, 7.0428, 7.0499],
[7.064 , 7.0569, 7.0499, ..., 7.0428, 7.0499, 7.0569]])
网格
# 画图 网格
import matplotlib.pyplot as plt
plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
Text(0.5,1,'Image plot of $\\sqrt{x^2 + y^2}$ for a grid of values')

plt.draw()
<Figure size 720x432 with 0 Axes>
plt.close('all')
Expressing Conditional Logic as Array Operations
# 将条件逻辑表述为数组运算
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
result = np.where(cond, xarr, yarr)
result
arr = np.random.randn(4, 4)
arr
arr > 0
np.where(arr > 0, 2, -2)
np.where(arr > 0, 2, arr) # set only positive values to 2
Mathematical and Statistical Methods
可以通过数组上的⼀组数学函数对整个数组或某个轴向的数据进
# ⾏统计计算。sum、mean以及标准差std等聚合计算
# (aggregation,通常叫做约简(reduction))既可以当做数组
# 的实例⽅法调⽤,也可以当做顶级NumPy函数使⽤。
# 数学和统计⽅法
# 可以通过数组上的⼀组数学函数对整个数组或某个轴向的数据进
# ⾏统计计算。sum、mean以及标准差std等聚合计算
# (aggregation,通常叫做约简(reduction))既可以当做数组
# 的实例⽅法调⽤,也可以当做顶级NumPy函数使⽤。
arr = np.random.randn(5, 4)
arr
arr.mean()
np.mean(arr)
arr.sum()
-3.1212770951357607
arr.mean(axis=1)
arr.sum(axis=0)
array([ 1.1644, -2.4154, -1.0308, -0.8396])
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7])
arr.cumsum()
array([ 0, 1, 3, 6, 10, 15, 21, 28], dtype=int32)
# 累加函数(如cumsum)
arr = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
arr
arr.cumsum(axis=0)
arr.cumprod(axis=1)
array([[ 0, 0, 0],
[ 3, 12, 60],
[ 6, 42, 336]], dtype=int32)
Methods for Boolean Arrays
arr = np.random.randn(100)
(arr > 0).sum() # Number of positive values
bools = np.array([False, False, True, False])
bools.any()
bools.all()
Sorting
# 排序
# 跟Python内置的列表类型⼀样,NumPy数组也可以通过sort⽅法
# 就地排序:
arr = np.random.randn(6)
arr
arr.sort()
arr
array([-1.1577, 0.0513, 0.4336, 0.8167, 1.0107, 1.8249])
arr = np.random.randn(5, 3)
arr
arr.sort(1)
arr
large_arr = np.random.randn(1000)
large_arr.sort()
large_arr[int(0.05 * len(large_arr))] # 5% quantile
Unique and Other Set Logic
唯⼀化以及其它的集合逻辑
# NumPy提供了⼀些针对⼀维ndarray的基本集合运算。最常⽤的
# 可能要数np.unique了,
# 唯⼀化以及其它的集合逻辑
# NumPy提供了⼀些针对⼀维ndarray的基本集合运算。最常⽤的
# 可能要数np.unique了,
names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
np.unique(names)
ints = np.array([3, 3, 3, 2, 2, 1, 1, 4, 4])
np.unique(ints)
array([1, 2, 3, 4])
sorted(set(names))
values = np.array([6, 0, 0, 3, 2, 5, 6])
np.in1d(values, [2, 3, 6])
array([ True, False, False, True, True, False, True])
File Input and Output with Arrays
# 4.4 ⽤于数组的⽂件输⼊输出
# np.save和np.load是读写磁盘数组数据的两个主要函数。
arr = np.arange(10)
np.save('some_array', arr)
np.load('some_array.npy')
np.savez('array_archive.npz', a=arr, b=arr)
arch = np.load('array_archive.npz')
arch['b']
np.savez_compressed('arrays_compressed.npz', a=arr, b=arr)
!rm some_array.npy
!rm array_archive.npz
!rm arrays_compressed.npz
Linear Algebra
线性代数(如矩阵乘法、矩阵分解、⾏列式以及其他⽅阵数学
# 等)是任何数组库的重要组成部分。不像某些语⾔(如
# MATLAB),通过*对两个⼆维数组相乘得到的是⼀个元素级的
# 积,⽽不是⼀个矩阵点积。因此,NumPy提供了⼀个⽤于矩阵
# 乘法的dot函数(既是⼀个数组⽅法也是numpy命名空间中的⼀
# 个函数):
# 线性代数(如矩阵乘法、矩阵分解、⾏列式以及其他⽅阵数学
# 等)是任何数组库的重要组成部分。不像某些语⾔(如
# MATLAB),通过*对两个⼆维数组相乘得到的是⼀个元素级的
# 积,⽽不是⼀个矩阵点积。因此,NumPy提供了⼀个⽤于矩阵
# 乘法的dot函数(既是⼀个数组⽅法也是numpy命名空间中的⼀
# 个函数):
x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
x
y
x.dot(y)
np.dot(x, y)
np.dot(x, np.ones(3))
x @ np.ones(3)
from numpy.linalg import inv, qr
X = np.random.randn(5, 5)
mat = X.T.dot(X)
inv(mat)
mat.dot(inv(mat))
q, r = qr(mat)
r
Pseudorandom Number Generation
numpy.random模块对Python内置的random进⾏了补充,增加了
# ⼀些⽤于⾼效⽣成多种概率分布的样本值的函数。例如,你可以
# ⽤normal来得到⼀个标准正态分布的4×4样本数组:
# 4.6 伪随机数⽣成
# numpy.random模块对Python内置的random进⾏了补充,增加了
# ⼀些⽤于⾼效⽣成多种概率分布的样本值的函数。例如,你可以
# ⽤normal来得到⼀个标准正态分布的4×4样本数组:
samples = np.random.normal(size=(4, 4))
samples
array([[-0.9975, 0.8506, -0.1316, 0.9124],
[ 0.1882, 2.1695, -0.1149, 2.0037],
[ 0.0296, 0.7953, 0.1181, -0.7485],
[ 0.585 , 0.1527, -1.5657, -0.5625]])
from random import normalvariate
N = 1000000
%timeit samples = [normalvariate(0, 1) for _ in range(N)]
%timeit np.random.normal(size=N)
np.random.seed(1234)
rng = np.random.RandomState(1234)
rng.randn(10)
Example: Random Walks
# 4.7 示例:随机漫步
import random
position = 0
walk = [position]
steps = 1000
for i in range(steps):
step = 1 if random.randint(0, 1) else -1
position += step
walk.append(position)
plt.figure()
<Figure size 720x432 with 0 Axes>
<Figure size 720x432 with 0 Axes>
# 折线图
plt.plot(walk[:100])
[<matplotlib.lines.Line2D at 0x18f0048f390>]

np.random.seed(12345)
nsteps = 1000
draws = np.random.randint(0, 2, size=nsteps)
steps = np.where(draws > 0, 1, -1)
walk = steps.cumsum()
walk.min()
walk.max()
(np.abs(walk) >= 10).argmax()
Simulating Many Random Walks at Once
nwalks = 5000
nsteps = 1000
draws = np.random.randint(0, 2, size=(nwalks, nsteps)) # 0 or 1
steps = np.where(draws > 0, 1, -1)
walks = steps.cumsum(1)
walks
walks.max()
walks.min()
hits30 = (np.abs(walks) >= 30).any(1)
hits30
hits30.sum() # Number that hit 30 or -30
crossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)
crossing_times.mean()
steps = np.random.normal(loc=0, scale=0.25,
size=(nwalks, nsteps))
Conclusion

##############################
自己的其他补充:
# 在-10和10之间生成一个数列,共100个数
x = np.linspace(-10, 10, 100)