一、逻辑运算
直接进行大小判断
score = np.random.randint(50, 100, (8, 5))
score
select_score = score[3:,:4] # 切取score数组中行下标为3至最后一行,列下标从0至第3的元素(左闭右开)
select_score
select_score > 80
----------------------------------------------------------------------
score2 = np.random.randint(50, 100, (3, 5)) # 生成3×5 值在[50,100)间的二维数组
score2
score2 > 90 # 逻辑判断, 若大于90则标记为True,否则为False
score2 == 99 # 判断是否存在99
score2[score2 > 60] = 1 # 布尔赋值, 将满足条件的标记为指定的值-布尔索引
score2
操作演示如下
二、通用判断函数
- np.all():所有元素为True,输出为True
- np.any():任意一个元素为True,输出为True
score3 = np.random.randint(50, 100, (3, 5)) # 生成3×5 值在[50,100)间的二维数组
score3
score3[0,0] = 100 # 修改一个
score3[0,2:4] = 0 # 修改连续多个
score3
np.all(score3[1,0:3] > 60)
np.all(score3[1,0:3] > 90)
np.any(score3[1,0:3] < 70)
np.any(score3[1,0:3] < 80)
三、三元运算符np.where
- np.where(condition, x, y):满足条件condition,输出x,不满足输出y
- 复合逻辑需要结合np.logical_and、np.logical_or和np.logical_not使用,对应与、或、非
代码如下
score4 = np.random.randint(50, 100, (3, 5)) # 生成3×5 值在[50,100)间的二维数组
score4
np.where(score4 > 88, 5, 2) # 符合指定条件标置为5,否则为2
np.where(np.logical_and(score4 > 70, score4 < 90), 1, 0) # 符合指定条件标置为1,否则为0
np.where(np.logical_or(score4 <= 70, score4 >= 90), 1, 0) # 符合指定条件标置为1,否则为0
np.where(np.logical_not(score4 <= 70, score4 >= 90), 1, 0) # 符合指定条件标置为1,否则为0
- 其他
- &或*:与
- |:或
score5 = np.random.randint(50, 100, (3, 5)) # 生成3×5 值在[50,100)间的二维数组
score5
np.where((score5 > 70)&(score5 < 90)) # 与,返回符合条件的行、列下标索引
np.where((score5 > 70)*(score5 < 90)) # 与
np.where((score5 < 70)&(score5 > 90)) # 与
np.where((score5 < 70)|(score5 > 90)) # 或,返回符合条件的行、列下标索引
np.where((score5 < 70))
四、统计运算
- np.min(a, axis):返回数组的最小值或沿axis轴的最小值
- np.max(a, axis]):返回数组的最大值或沿axis轴的最大值
- np.median(a, axis):计算沿指定轴axis的中位数
- np.mean(a, axis, dtype):计算沿指定轴axis的算术平均值
- np.std(a, axis, dtype):计算沿指定轴axis的标准偏差
- np.var(a, axis, dtype):计算沿指定轴axis的方差
- 统计时,axis 轴的取值不定,Numpy中不同的API轴的值都不一样,在这里,axis=0代表列, axis=1代表行去进行统计
- np.argmax(a, axis):获取指定每一行或列中最大值索引下标
- np.argmin(a, axis):获取指定每一行或列中最小值索引下标
代码如下
score6 = np.random.randint(30, 100, (3, 5)) # 生成3×5 值在[50,100)间的二维数组
score6
np.min(score6, axis=0) # 统计每一列中的最小值,axis=0为列,axis=1为行
np.max(score6, axis=0) # 统计每一列中的最大值
np.max(score6, axis=1) # 统计每一行中的最大值,axis=1为行
np.median(score6, axis=0) # 统计每一列中的中位数
np.mean(score6, axis=0) # 统计每一列中的算数平均值
np.std(score6, axis=0) # 统计每一列中的标准偏差
np.var(score6, axis=0) # 统计每一列中的方差
np.argmax(score6, axis=0) # 获取每一列中最大值所在的行的索引下标
np.argmin(score6, axis=0) # 获取每一列中最小值所在的行的索引下标
演示结果如下
学习导航:http://xqnav.top/