NumPy作业(2)


题目

numpy作业2-1 numpy作业2-1

import numpy as np
# 1题 
arr1 = np.arange(9).reshape(3,3)
arr1.max(axis=1) # 对于二维数组来说,axis=0 对列操作,axis=1 对行操作
array([2, 5, 8])
# 2题
arr2 = np.arange(36).reshape(2,3,6)
arr2
array([[[ 0,  1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10, 11],
        [12, 13, 14, 15, 16, 17]],

       [[18, 19, 20, 21, 22, 23],
        [24, 25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34, 35]]])
# transpose 替换不同维度上的元素的数量,返回结果是将数组进行重组
arr3 = np.transpose(arr2,axes=(2,1,0))
arr3
array([[[ 0, 18],
        [ 6, 24],
        [12, 30]],

       [[ 1, 19],
        [ 7, 25],
        [13, 31]],

       [[ 2, 20],
        [ 8, 26],
        [14, 32]],

       [[ 3, 21],
        [ 9, 27],
        [15, 33]],

       [[ 4, 22],
        [10, 28],
        [16, 34]],

       [[ 5, 23],
        [11, 29],
        [17, 35]]])
arr3.shape
(6, 3, 2)
# 3题
# 返回修改完类型后的返回值,原数组类型不变。
# astype方法可以修改类型
arr4 = arr3.astype("f8")
arr4
array([[[ 0., 18.],
        [ 6., 24.],
        [12., 30.]],

       [[ 1., 19.],
        [ 7., 25.],
        [13., 31.]],

       [[ 2., 20.],
        [ 8., 26.],
        [14., 32.]],

       [[ 3., 21.],
        [ 9., 27.],
        [15., 33.]],

       [[ 4., 22.],
        [10., 28.],
        [16., 34.]],

       [[ 5., 23.],
        [11., 29.],
        [17., 35.]]])
arr4.dtype
dtype('float64')
# 4题 2,2   3,4

arr5 = np.arange(16).reshape(4,4)
arr5
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
arr5[1,1],arr5[2,3]
(5, 11)
# 5题 1~2行   2~3列
arr5[:2]
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
arr5[:,1:3]
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10],
       [13, 14]])
# 一次取出
arr5[:2,1:3]
array([[1, 2],
       [5, 6]])
# 6  2行 1~3
arr5[1,:3]
array([4, 5, 6])
# 7 
arr5[1,[0,2]]
array([4, 6])
# 8题
arr5[2,2],arr5[1,3]
(10, 7)
# 9题
student_name = np.array(['Tom','Lily','Jack','Rose'])

student_sore = np.random.randint(70,90,size=(4,3))
student_sore
array([[85, 73, 89],
       [83, 87, 87],
       [80, 80, 71],
       [70, 72, 88]])
arr6 = student_name == 'Rose'
arr6
array([False, False, False,  True])
student_sore[arr6]
array([[70, 72, 88]])