numpy的ndarray的运算

ndarray的运算

1.逻辑运算

score = np.random.randint(40,100,(10,5))#生成一个10行5列取值在40-50之间的数组
test_sore = score[6:,0:5]#从第6行开始到末尾,5列,取出4名同学用于逻辑判断

test_sore>60
test_sore
"""
array([[ 1, 56,  1,  1, 40],
       [59,  1, 49,  1,  1],
       [50, 43,  1,  1,  1],
       [43,  1, 56,  1,  1]])
"""

test_sore[test_sore>60] = 1#此时我深拷贝
test_sore
"""
array([[ 1, 56,  1,  1, 40],
       [59,  1, 49,  1,  1],
       [50, 43,  1,  1,  1],
       [43,  1, 56,  1,  1]])
"""


2.通用判断函数

  • np.all()
#判断前2名同学的乘积[0:2,:]是否全及格
np.all(score[0:2,:] > 60)#
False
  • np.any()
#判断前两名同学的成绩[0:2,:]是否有大于90分的
np.any(score[0:2,:] > 80)
True

3.np.where(三元运算符)

  • 通过使用np.where能够进行更加复杂的运算
  • np.where()
#判断前四名学生,前四门课程中,成绩中大于60的值为1,否则为0
temp = score[:4,:4]
np.where(temp > 60,1,0)
  • 复合逻辑需要结合np.logical_andnp.logical_or使用
#判断前四名学生,前四门课程中,成绩大于60且小于90的转换为1,否则为0
np.where(np.logical_and(temp > 60,temp < 90),1,0)

#判断前四名学生,前四门课程中,成绩中大于90或小于60的转换为1,否则为0
np.where(np.logical_or(temp > 90,temp < 60),1,0)

4.统计指标

  • 在数据挖掘/机器学习领域,统计指标的值也是我们分析问题的一种方式,常见的指标如下:
  • min(a,axis)
  • max(a,axis)
  • median(a,axis)
  • mean(a,axis,dtype)
  • std(a,axis,dtype)
  • var(a,axis,dype)
temp = score[:4,0:5]
print("前四名学生,各科成绩的最高分:{}".format(np.max(temp,axis=0)))
print("前四名学生,各科成绩的最低分:{}".format(np.min(temp,axis=0)))
print("前四名学生,各科成绩的波动情况:{}".format(np.std(temp,axis=0)))
print("前四名学生,各科成绩的平均分:{}".format(np.mean(temp,axis=0)))

"""
前四名学生,各科成绩的最高分:[94 87 94 96 90]
前四名学生,各科成绩的最低分:[45 41 66 53 43]
前四名学生,各科成绩的波动情况:[18.5876303  18.3507493   9.97496867 17.18284028 17.42125139]
前四名学生,各科成绩的平均分:[63.  64.5 81.  82.5 63. ]
"""

#寻找相应的下标
print("前四名学生,各科成绩最高分对应的学生下标:{}".format(np.argmax(temp,axis=0)))
print("前四名学生,各科成绩最低分对应的学生下标:{}".format(np.argmin(temp,axis=0)))
"""
前四名学生,各科成绩最高分对应的学生下标:[0 1 1 1 2]
前四名学生,各科成绩最低分对应的学生下标:[2 3 0 0 3]
"""
posted @ 2023-02-24 11:04  小杨的冥想课  阅读(22)  评论(0编辑  收藏  举报