1.利用数组进行数据处理
Numpy可以使你将许多中种数据处理任务表述为简洁的数组表达式.(否则需要编写循环).用数组表达式代替循环的做法,通常被称为矢量化.
以下是矢量化的一个例子:
import numpy as np import matplotlib.pyplot as plt points=np.arange(-5,5,0.01)#1000个间隔相等的点 xs,ys=np.meshgrid(points,points) z=np.sqrt(xs**2+ys**2) plt.imshow(z,cmap=plt.cm.gray); plt.colorbar() plt.title("Image plot of $sqrt{x^2+y^2}$ for a grid of values")
下面是画出来的第一幅图片:
2.小插曲:python中plt.imshow(img)显示不了图片
import pylab
然后在plt.imshow()这一步后加上
pylab.show()
就可以显示了
或者直接plt.show()就可以了,新手经常出现这个低级的问题
3.将条件逻辑表述为数组运算
1)假设有一个布尔数组和两个值数组:
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,True,False])
想要根据cond中值选取xarr和yarr中的值.当cond中的值为True时,选取xarr的值,否则从yarr中选取.
列表推导式的写法:
result=[(x if c else y)for x,y, c in zip(xarr,yarr,cond)]
更加简洁而高效率的写法:
result=np.where(cond,xarr,yarr)
2)假设有一个随机数据组成的矩阵,希望将所有正值替换为2,将所有负值替换为-2
In [25]: import numpy as np In [26]: arr=np.random.randn(4,4) In [27]: arr Out[27]: array([[ 2.15965747, 1.10228918, -0.04143705, 0.26530682], [-0.7299881 , -0.84176449, 0.71031421, -1.06833011], [-1.90799121, 0.24842699, 0.05394588, -1.97281055], [ 0.46710425, -0.76024439, -0.98944968, 0.46877683]]) In [28]: np.where(arr>0,2,-2) Out[28]: array([[ 2, 2, -2, 2], [-2, -2, 2, -2], [-2, 2, 2, -2], [ 2, -2, -2, 2]])
In [29]:
...: #z若只将正值替换为2
...: np.where(arr>0,2,arr)
Out[29]:
array([[ 2. , 2. , -0.04143705, 2. ],
[-0.7299881 , -0.84176449, 2. , -1.06833011],
[-1.90799121, 2. , 2. , -1.97281055],
[ 2. , -0.76024439, -0.98944968, 2. ]])
3)利用np.where实现更复杂的逻辑
result=[] for i in range(n) if cond1[i]and cond2[i]: result.append(0) elif cond1[i]: result.append(1) elif cond2[i]: result.append(2) else: result.append(3)
可以改写成一个嵌套的where表达式:
np.where(cond1&cond2,0, np.where(cond1,1, np.where(cond2,2,3)))
可以利用"布尔值在计算过程中可以被当做0或1处理",神神秘秘的写成这个样子:
result=1*(cond1-cond2)+2*(cond2 & -cond1)+3*-(cond1|cond2)