Python3--我的代码库之numpy索引(三)

1. 准备工作

import numpy as np
A = np.arange(3,15)
B = A.reshape((3,4))

1.1. 查询第三个元素

print(A[2]) #索引从0开始

1.2. 查询第二列的元素

B[:,1]

Out:
array([ 4, 8, 12])

1.3. 查询第二行、第三列右下角的所有值

B[1:,2:]

Out:
array([[ 9, 10],
[13, 14]])

1.4. 迭代行

# 默认的是按照一行为迭代
for row in B:
    print("这是一次输出!",row)

Out:
这是一次输出! [3 4 5 6]
这是一次输出! [ 7 8 9 10]
这是一次输出! [11 12 13 14]

1.5. 迭代列

# 转置后按行迭代,既是按列迭代
for row in B.T:
    print("这是一次输出!",row)

Out:这是一次输出! [ 3 7 11]
这是一次输出! [ 4 8 12]
这是一次输出! [ 5 9 13]
这是一次输出! [ 6 10 14]

1.6. 迭代每一个值

1.6.1 方法一

# 打印矩阵的每一个值
for item in A[range(len(A))]:
    print(item)

Out:3
4
5
6
7
8
9
10
11
12
13
14

1.6.1 方法二

B.flatten() #迭代方法

Out: array([ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

 for item in A.flat:
    print(item)

Out:3
4
5
6
7
8
9
10
11
12
13
14

猜你喜欢

转载自blog.csdn.net/c_air_c/article/details/81089033