主要内容
1) 利用数组进行数据处理
2) 将条件逻辑表述为数组运算
3) 数学与统计方法
4) 用于布尔型数组的方法
5) 排序
6) 唯一化以及其他的集合逻辑
7) 用于数组的文件输入输出
8) 线性代数
1) 利用数组进行数据处理
import numpy as np
points = np.arange(-5,5,1)
print points
xs,ys = np.meshgrid(points,points)
ys
[-5 -4 -3 -2 -1 0 1 2 3 4]
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
[-4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
[-3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
[-2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]])
xs
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]])
2) 将条件逻辑表述维数组运算
np.where()函数是三元表达式:x if condition else y 的矢量化版本,假设,我们有一个布尔数组和两个数组
xarr = np.array([1,2,3,4,5])
yarr = np.array([6,7,8,9,10])
cond = np.array([True,False,True,True,False,])
加入我们想根据cond数组的情况来选取xarr或yarr数组中的值,有两种方法,一种是列表推导式,另外一种是矢量化
##列表推导式
%timeit result = [(x if c else y) for x,y,c in zip(xarr,yarr,cond)]
The slowest run took 14.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.77 µs per loop
result
[1, 7, 3, 4, 10]
## 矢量化
%timeit result = np.where(cond,xarr,yarr)
The slowest run took 13.14 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 827 ns per loop
result
array([ 1, 7, 3, 4, 10])
从上述结果真可以看出,矢量化的计算速度大概是列表计算的三倍,注意返回结果类型的不一致!np.where函数的参数还可以是标量
arr = np.random.randn(4,4)
arr
array([[ 0.81362115, -0.59091357, 0.04834518, 0.31279457],
[ 0.14034937, -0.495634 , -1.65939013, -0.06717819],
[ 1.27779012, 1.00333966, -1.89590419, 0.06417592],
[-0.39706132, -0.55924097, 0.19493047, -2.09199616]])
np.where(arr>0,2,-2)
array([[ 2, -2, 2, 2],
[ 2, -2, -2, -2],
[ 2, 2, -2, 2],
[-2, -2, 2, -2]])
arr
array([[ 0.81362115, -0.59091357, 0.04834518, 0.31279457],
[ 0.14034937, -0.495634 , -1.65939013, -0.06717819],
[ 1.27779012, 1.00333966, -1.89590419, 0.06417592],
[-0.39706132, -0.55924097, 0.19493047, -2.09199616]])
注意,条件逻辑表达式不改变原数组
np.where(arr>0,2,arr)