1.面向数组示例
本案例模拟 ( x 2 + y 2 ) 2 \sqrt[2]{(x^2+y^2)} 2(x2+y2)的数据分布,代码如下
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")

2.条件逻辑操作
使用numpy.where(condition,true_value,false_value),即对于数组中的任意元素,若为真则赋true_value,否则赋为false_value,如下例:
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)
result
'''
array([1.1, 2.2, 1.3, 1.4, 2.5])
'''
arr = np.random.randn(4, 4)
arr
arr > 0
np.where(arr > 0, 2, -2)
'''
array([[-0.2047, 0.4789, -0.5194, -0.5557],
[ 1.9658, 1.3934, 0.0929, 0.2817],
[ 0.769 , 1.2464, 1.0072, -1.2962],
[ 0.275 , 0.2289, 1.3529, 0.8864]])
array([[False, True, False, False],
[ True, True, True, True],
[ True, True, True, False],
[ True, True, True, True]])
array([[-2, 2, -2, -2],
[ 2, 2, 2, 2],
[ 2, 2, 2, -2],
[ 2, 2, 2, 2]])
'''
np.where(arr > 0, 2, arr) # set only positive values to 2
'''
array([[-0.2047, 2. , -0.5194, -0.5557],
[ 2. , 2. , 2. , 2. ],
[ 2. , 2. , 2. , -1.2962],
[ 2. , 2. , 2. , 2. ]])
'''
3.布尔数组操作
布尔数组即True和False组成的数组,需要注意的是在numpy中True=1,False=0,本节所讲的函数也可用于只包含0,1的数组中。顺着这个逻辑也可继续推出,通用函数也可作用过于布尔数组中,例如sum函数。
而布尔数组也有特殊的函数存在,例如any和all方法,在该方法下会检查数组中是否有一个True或者每一个值都为True。
805

被折叠的 条评论
为什么被折叠?



