一、数组的基本操作
1. 数组的索引、切片
多维数组的索引方式(直接用连续的多个下标值来访问):
2. 形状修改
ndarray.reshape(shape, order)
· 返回一个具有相同数据域,但shape不一样的数组
· 行、列不进行互换
ndarray.resize(new_shape)
· 修改数组本身的形状(需要保持元素个数前后相同)
· 行、列不进行互换
ndarray.T
· 数组的转置(行、列互换)
3. 类型修改
ndarray.astype(type)
· 返回修改了类型之后的数组
4. 数组去重
np.unique(temp)
· 去掉重复的数字
二、ndarray运算
1. 逻辑运算
# 逻辑运算
score = np.random.randint(40, 100, (10,5))
test_score = score[6:, 0:5]
print(test_score > 60) # 直接大于小于判断
test_score[test_score > 60] = 1 # 满足要求赋值为1
2. 通用判断函数(判断某一个区域的所有值or存在值)
# 通用判断函数
# 判断前两名同学的所有科目成绩[0:2, :]是否全部及格
npall = np.all(score[0:2, :] > 60)
# 判断前两名同学的所有科目成绩[0:2, :]是否有大于90分的
npany = np.any(score[0:2, :] > 90)
3. 三元运算符(将某些满足条件的值、不满足条件的值记为特殊值)
# 三元运算符
# 判断前四名学生,前四门课程,成绩大于60的置为1,否则为0
np1 = np.where(score[:4, :4] > 60, 1, 0)
# 逻辑与和逻辑或
np2 = np.where(np.logical_and(score[:4, :4] > 60, score[:4, :4] < 90), 1, 0)
np3 = np.where(np.logical_or(score[:4, :4] < 60, score[:4, :4] > 90), 1, 0)
4. 统计指标
# 统计指标
# 求取某一个数据区域的最大值、最小值、平均值、波动情况等
temp = score[:4, 0:5]
# axis表示对行或者列进行统计
# 指定列 统计
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)))
# 求取最大值和最小值对应的下标
# np.argmax(temp, axis=)
# np.argmin(temp, axis=)
print("前四名学生中,各科成绩的最大分对应学生下标:{}".format(np.argmax(temp, axis=0)))
print("前四名学生中,各科成绩的最小分对应学生下标:{}".format(np.argmin(temp, axis=0)))