加载中...

02numpy_切片索引_对象属性

numpy_ndarray对象属性

numpy最重要的一个特征是其N维数组对象ndarray,它是一系列同类型数据的集合,以0下表为开始进行集合中的元素索引

属性 说明
.ndim 秩,即轴的数量或维度的数量
.shape ndarray对象的尺度,对于矩阵,n行m列
.size ndarray对象元素的数量,相当于.shape中的$n*m$的值
.dtype ndarray对象的元素类型
.itemsize ndarray对象中的每个元素的大小,以节点为单位
import numpy as np
aa = np.array([[1,2,3],[4,5,6],[7,8,9]])
# .ndim
aa.ndim
# .size
aa.size
# .shape
aa.shape
# .dtype
aa.dtype
# .itemsize,字节为单位,一个字节8位
aa.itemsize

numpy_创建单位矩阵

alt text

单位矩阵从左上角到右下角的对角线元素均为1,除此之外全都是0。任何矩阵与单位矩阵相乘都等于本身。

【语法格式】

numpy.eye(参数1,dtype=int)
numpy.identity(参数1,dtype=int)

【参数说明】

  • 参数1:指定维度大小
  • dtype: 指定数组元素的数据类型

【示例】eyeidentity的使用

n1 = np.eye(3,dtype=int)
n2 = np.identity(3,dtype=int)

linspace函数创建等差数列

alt text

linspace函数用于创建一个一维数组,数组中元素是由一个等差数列构成

【语法格式】

numpy.linspace(start,stop,num=50,endpoint=True,retstep= False, dtype=None)

【参数说明】

  • start: 序列起始值
  • stop: 序列终止值
  • num: 要生成的等步长的样本数量,默认为50
  • endpoint: 该值为True时,数列包含stop的值,反之不包含;默认为True
  • retstep: 该值为True时,生成的数组中会显示间距,反之不显示
  • dtype:ndarray的数据类型

【示例】linspace函数的使用

## 创建等差数列
np.linspace(1,5,5)
# 指定类型
np.linspace(1,5,5,dtype=int)
# 显示间距
np.linspace(1,5,5,retstep=True)

# 默认endpoint=True,即包含5
np.linspace(1,5,5,endpoint=True,retstep=True)
np.linspace(1,5,5,endpoint=False,retstep=True)

logspace函数创建等比数列

alt text

【语法格式】

numpy.logspace(start,stop,num=50,endpoint=True,base= 10.0, dtype=None)

【参数说明】

  • start: 序列起始值为:base * start
  • stop: 序列起始值为:base * stop
  • num: 要生成的等步长的样本数量,默认为50
  • endpoint: 该值为True时,数列包含base * stop的值,反之不包含;默认为True
  • base:
  • dtype:ndarray的数据类型

【示例】logspace函数的使用

# 等比数列
# 1,2,4,8,16
# 2^0, 2^1, 2^2, 2^3, 2^4

np.logspace(0,4,base=2,num=5,dtype=int)

切片和索引

ndarray对象的内容可以通过索引或切片来访问,这与python当中的list的切片操作一样
ndarray数组可以基于0~n下标进行索引,并设置start,stop以及step参数进行,从原来的数组中切割出一个新的数组

【参数说明】

  • start:起始索引值,默认为0
  • stop:结束索引值,不包括该索引对应的值
  • step:步长,默认为1

一维数组

image-20250506150701426

【示例】一维数组索引和切片的使用

my_list = [1,2,3,4,5]
my_array = np.array(my_list)
# 索引
my_array[0]
# 最大索引值:len(my_array)-1
my_array[4] 
# 负索引
my_array[-1] 
# 切片: start: stop: step
my_array[1:3:2]
my_array[-2:]
#stop:可以超出最大索引值
my_array[1:10]
# 数组元素反向输出
my_array[::-1]

二维数组

image-20250506152528734

【示例】二维数组索引和切片的使用

my_array = np.arange(1,25).reshape(4,6)
my_array
# 获取数值9
# 数组[行索引,列索引]
my_array[1][2]
# 获取整行 数组[行索引]
my_array[1]
# 获取整列 数组[列索引]
my_array[:,2]
# 获取部分行部分列  数组[行切片,列切片]
my_array[:2,:]
my_array[:,1:4]
# 对行和列同时切片
my_array[::2,::2]
# 同时获取第三行第二列,第四行第一列
my_array[(2,3),(1,0)]

关于二维数组负索引的举例之后上传到gitee请注意查收
【示例】切片数组的复制

np.copy()函数能够使得我们将原始的数组部分或整体赋值给其他数组时,当改变新数组当中的某个元素的值时,原始数组当中的对应的元素值不发生改变

my_array = np.arange(1,25).reshape(4,6)
my_array
sub_a = my_array[:2,:2]
sub_a[0,0] = 100

sub_b = np.copy(my_array[:2,:2])
sub_b[0][0] = 200
posted @ 2025-05-06 15:59  一只小小小飞猪  阅读(27)  评论(0)    收藏  举报