numpy 索引和切片

一、取行

1、单行

数组[index, :]
# 取第index+1行

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
# 取第2行数据
row1 = arr1[1, :]
print(row1)

2、连续的多行

数组[start:end , :]
# 顾头不顾尾,也可以使用步长,不过一般不用

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(6, 4)
# 取第2、3、4行数据
row1 = arr1[1:4, :]
print(row1)

3、不连续的多行

数组[[index1, index2] , :]
# 取index1+1 和index2+1 行

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(6, 4)
# 取第1、4、2行
row1 = arr1[[0, 3, 1], :]
print(row1)

二、取列

1、单列

数组[:, index]
# 取第index+1列

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
# 取第3列
cols = arr1[:, 2]
print(cols)

2、连续的多列

数组[:, start:end]
# 顾头不顾尾,索引从0开始

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
# 取列数大于等于3的所有列
cols = arr1[:, 2:]
print(cols)

3、不连续的多列

数组[:, [index1, index2]]
# 取第index1+1和index2+1列

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
# 取列数大于等于3的所有列
cols = arr1[:, 2:]
print(cols)

三、取行和列

1、单个数据

数组[row,col]
# 取第row+1行和第col+1列,对应的数据

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
# 取第3行第4列的值
data = arr1[2, 3]
print(data)

2、连续的行和列

数组[start:end, start:end]
# 行start+1到end,列start+1到end

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
# 取第2到3行和第3列之后的数据
data = arr1[1:3, 2:]
print(data)

3、不连续的多个数据

数组[[a, b] ,[c, d]]
# 取第a+1行和第c+1列相交的数据
# 取第b+1行和第d+1列相交的数据

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
#
data = arr1[[0, 3], [3, 5]]
print(data)

 

posted @ 2019-11-28 23:29  市丸银  阅读(130)  评论(0编辑  收藏  举报