Python中的NumPy(二)——索引(Indexing)

版权声明:本文版权归作者所有,未经允许不得转载! https://blog.csdn.net/m0_37827994/article/details/86494105

索引

1、索引

  • 索引的时候要用中括号,即 x[0]
# Indexing
x = np.array([1, 2, 3])
print ("x[0]: ", x[0])
x[0] = 0
print ("x: ", x)

输出结果:

x[0]:  1
x:  [0 2 3]

2、Slicing

# Slicing
x = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print (x)
print ("x column 1: ", x[:, 1]) 
print ("x row 0: ", x[0, :]) 
print ("x rows 0,1,2 & cols 1,2: \n", x[:3, 1:3]) 

输出结果:

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
x column 1:  [ 2  6 10]
x row 0:  [1 2 3 4]
x rows 0,1,2 & cols 1,2: 
 [[ 2  3]
 [ 6  7]
 [10 11]]

3、整数数组索引

# Integer array indexing
x = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print (x)
rows_to_get = np.arange(len(x))
print ("rows_to_get: ", rows_to_get)
cols_to_get = np.array([0, 2, 1])
print ("cols_to_get: ", cols_to_get)
print ("indexed values: ", x[rows_to_get, cols_to_get])

输出结果:

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
rows_to_get:  [0 1 2]
cols_to_get:  [0 2 1]
indexed values:  [ 1  7 10]

解释:(0,0)位置是1;(1,2)位置是7;(2,1)位置是10

4、布尔数组索引

# Boolean array indexing
x = np.array([[1,2], [3, 4], [5, 6]])
print ("x:\n", x)
print ("x > 2:\n", x > 2)
print ("x[x > 2]:\n", x[x > 2])

输出结果:

x:
 [[1 2]
 [3 4]
 [5 6]]
x > 2:
 [[False False]
 [ True  True]
 [ True  True]]
x[x > 2]:
 [3 4 5 6]

猜你喜欢

转载自blog.csdn.net/m0_37827994/article/details/86494105