numpy 数据处理

np.meshgrid()

meshgrid 传入两个一维数组,返回第一个二维数组用第一个传入的一维数组为行,第二个传入的一维数组为列
返回的第二个数组是以第二个传入的一维数组为行,第一个一维数组为列

import numpy as np
import matplotlib.pyplot as plt
import pylab
points = np.arange(-5,5,0.01)
#meshgrid 传入两个一维数组,返回第一个二维数组用第一个传入的一维数组为行,第二个传入的一维数组为列
#返回的第二个数组是以第二个传入的一维数组为行,第一个一维数组为列
xs,ys = np.meshgrid(points,points)
print(xs == ys.T)  #True

z = np.sqrt(ys**2 + xs**2)
plt.imshow(z,cmap= plt.cm.gray)
plt.colorbar()
pylab.show()

筛选

真值表

#真值表
import numpy as np
import numpy.random as np_random
x_arr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
y_arr = 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(x_arr, y_arr, cond)] # 通过列表推到实现
print(result)


where:掩码if筛选

#若where的第2、3个参数不是数组,则第2、3个参数将通过掩码组成掩码形状相同的数组
np.where(cond,x_arr,y_arr)
arr = np_random.randn(4,4)
print(arr)
print(np.where(arr>0,2,-2))

#where多条件

cond_1 = np.array([True, False, True, True, False])
cond_2 = np.array([False, True, False, True, False])
# 传统代码如下
result = []
for i in range(len(cond)):
    if cond_1[i] and cond_2[i]:
        result.append(0)
    elif cond_1[i]:
        result.append(1)
    elif cond_2[i]:
        result.append(2)
    else:
        result.append(3)
print(result)
result = np.where(cond_1 & cond_2, 0, 
                  np.where(cond_1, 1, np.where(cond_2, 2, 3)))
原文地址:https://www.cnblogs.com/echoboy/p/9520880.html