数据分析 numpy数组_05索引

数据分析 numpy数组_05-numpy数组操作

1、索引

1、调用slice函数,指定start,stop,step

2、通过'',指定start,stop,step

3、通过'',来使选择元组的长度与数组的维度相同的ndarra,[行,列]!

4、通过整数数组索引指定位置的元素

5、通过''''索引

6、布尔索引,使用布尔运算符筛选符合条件的元素

7、花式索引,利用整数数组进行索引

  1、调用slice函数,指定start,stop,step

import numpy as np

x = np.arange(12)
y = slice(2, 10, 2)
print(x[y])

  2、通过'',指定start,stop,step

import numpy as np

x = np.arange(12)
print(x[2:10:2])

  3、通过'',来使选择元组的长度与数组的维度相同的ndarra,[行,列]!

import numpy as np

x = np.arange(12)
print(x[..., 2]) 

  4、通过整数数组索引指定位置的元素

import numpy as np

x = np.arange(12)
y = x.reshape(3, 4)
print(y[[0, 1, 2], [0, 1, 0]])    # 获取数组中(0,0),(1,1)和(2,0)位置处的元素
import numpy as np

x = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
print(x)
rows = np.array([[0, 0], [3, 3]])    # 行索引
cols = np.array([[0, 2], [0, 2]])    # 列索引
y = x[rows, cols]
print('这个数组的四个角元素是:')
print(y)

  5、通过':''…'索引,

import numpy as np
 
x = np.array([[1,2,3], [4,5,6],[7,8,9]])
y = x[1:3, 1:3]
z = y[1:3,[1,2]]
i = x[...,1:]
print(y)
print(z)
print(i)

  6、布尔索引,通过布尔运算符筛选符合条件的元素

import numpy as np 
 
x = np.array([[  0,  1,  2],[  3,  4,  5],[  6,  7,  8],[  9,  10,  11]])  
print ('我们的数组是:')
print (x)
print ('
')
# 现在我们会打印出大于 5 的元素  
print  ('大于 5 的元素是:')
print (x[x >  5])

  7、花式索引,用整数数组进行索引。花式索引根据索引数组的值作为目标数组的某个轴的下标来取值。花式索引跟切片不一样,它总是将数据复制到新数组中。对于使用一维整型数组作为索引,如果目标是一维数组,那么索引的结果就是对应位置的元素;如果目标是二维数组,那么就是对应下标的行。

import numpy as np

x = np.arange(32).reshape((8, 4))
print(x[[4, 2, 1, 7]])         # 顺序索引数组,因为是二位数组,所以4,2,1,7分别为二位数组的第5,3,2,8行
print(x[[-4, -2, -1, -7]])     # 倒序索引数组,因为是二位数组,所以-4,-2,-1,-7分别为二位数组的第5,7,8,2行

  

原文地址:https://www.cnblogs.com/yinminbo/p/11425689.html