python-数组3

#利用数组进行数据处理
points=np.arange(-5,5,0.01)#1000个间隔相等的点
xs,ys=np.meshgrid(points,points)#np.meshgrid产生两个二维数组
#print('this is xs',xs)

#print('this is ys:',ys)
import matplotlib.pyplot as plt
z=np.sqrt(xs**2+ys**2)
#print(z)
plt.imshow(z,cmap=plt.cm.gray);plt.colorbar()
plt.title('image plot of $\sqrt{x^2+y^2}$ for a grid of value')

python-数组3

#将条件逻辑表述为数组运算:

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=np.where(cond,xarr,yarr)
#print(result)
'''结果:
[1.1 2.2 1.3 1.4 2.5]'''
arr=randn(4,4)

#print(arr)
#print(np.where(arr>0,2,-2))#arr中大于0的设为2,否则为-2
#print(np.where(arr>0,2,arr))
result=[]
cond1=np.array([True,False,True,True,False])
cond2=np.array([True,True,True,False,False])
for i in range(len(cond1)):
    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)     
print(result)
'''结果:[0, 2, 0, 1, 3]'''
print('other way is npwhere',np.where(cond1&cond2,0,np.where(cond1,1,np.where(cond2,2,3))))
'''结果:other way is npwhere [0 2 0 1 3]'''