numpy-创建数组

numpy-创建数组

Ndarray 对象

NumPy 中定义的最重要的对象是称为 ndarray 的 N 维数组类型。 它描述相同类型的元素集合。可以使用基于零的索引访问集合中的项目。ndarray中的每个元素在内存中使用相同大小的块。 ndarray中的每个元素是数据类型对象的对象(称为dtype)。

N 维数组对象 ndarray,一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引

内部组成

  • 一个指向数据(内存或内存映射文件中的一块数据)的指针。
  • 数据类型或 dtype,描述在数组中的固定大小值的格子。
  • 一个表示数组形状(shape)的元组,表示各维度大小的元组。
  • 一个跨度元组(stride),其中的整数指的是为了前进到当前维度下一个元素需要"跨过"的字节数。
总结
1、存储类型相同
2、每个元素存储大小相同
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0) 

"""
object 
dtype        数组的期望数据类型
copy          对象被复制
order          C(行主)或F(列主)或A(任何)(默认) 
subok        默认情况下,返回的数组被强制为基类数组。如果为true,则通过子类 
ndmin        指定结果数组的最小维数
"""

数据类型

numpy 的数值类型实际上是 dtype 对象的实例,并对应唯一的字符

type 描述
bool_ 布尔型数据类型(True 或者 False)
int_ 默认的整数类型(类似于 C 语言中的 long,int32 或 int64)
intc 与 C 的 int 类型一样,一般是 int32 或 int 64
intp 用于索引的整数类型(类似于 C 的 ssize_t,一般情况下仍然是 int32 或 int64)
int8 字节(-128 to 127)
int16 整数(-32768 to 32767)
int32 整数(-2147483648 to 2147483647)
int64 整数(-9223372036854775808 to 9223372036854775807)
uint8 无符号整数(0 to 255)
uint16 无符号整数(0 to 65535)
uint32 无符号整数(0 to 4294967295)
uint64 无符号整数(0 to 18446744073709551615)
float_ float64 类型的简写
float16 半精度浮点数,包括:1 个符号位,5 个指数位,10 个尾数位
float32 单精度浮点数,包括:1 个符号位,8 个指数位,23 个尾数位
float64 双精度浮点数,包括:1 个符号位,11 个指数位,52 个尾数位
complex_ complex128 类型的简写,即 128 位复数
complex64 复数,表示双 32 位浮点数(实数部分和虚数部分)
complex128 复数,表示双 64 位浮点数(实数部分和虚数部分)
str
unicode
object
# 显示数组的属性
import numpy as np

arr=np.array([1.1, 1.2])
print(arr)
# [1.1, 1.2]
print(arr.dtype)
# dtype('float64')

类型转换

方法1

arr=np.array([0,1,2,3,4,5])
arr2=np.array(arr,dtype=np.float32)
print(arr.dtype)
print(arr2.dtype)

方法2

arr.astype(np.int16)

# 
arr=np.array([1.1, 1.2])
print(arr.dtype)
# dtype('float64')
arr.astype(np.int16)
print(arr,dtype)
# dtype('int16')

数组属性

ndarray对象的属性

ndarray.ndim          秩,即轴的数量或维度的数量
ndarray.shape         数组的维度,对于矩阵,n 行 m 列
ndarray.size          数组元素的总个数,相当于 .shape 中 n*m 的值
ndarray.dtype         ndarray 对象的元素类型
ndarray.itemsize      ndarray 对象中每个元素的大小,以字节为单位
ndarray.flags         ndarray 对象的内存信息
ndarray.real          ndarray元素的实部
ndarray.imag          ndarray 元素的虚部
ndarray.data          包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性。

注释: 属性后面没有括号
import numpy as np

# ------------------------------------一维数组
a1 = np.array([1, 2, 3, 4, 5])
print('a1的维度:', a1.shape)  # a1的维度: (5,)
print('a1的秩求法1:', a1.ndim)  # a1的秩求法1: 1
print('a1的秩求法2:', len(a1.shape))  # a1的秩求法2: 1
print('a1的数组元素个数:', a1.size)  # a1的数组元素个数: 5
print('a1的缓存区:', a1.data)  # a1的缓存区: <memory at 0x000001BD028A0108>
print('a1的元素类型:', a1.dtype)  # a1的元素类型: int32
print('a1的字节大小:', a1.itemsize)  # a1的字节大小: 4

# ------------------------------------多维数组
a2 = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)])
print('a2的维度:', a2.shape)  # a2的维度: (3, 3)
print('a2的秩求法1:', a2.ndim)  # a2的秩求法1: 2
print('a2的秩求法2:', len(a2.shape))  # a2的秩求法2: 2
print('a2的数组元素个数:', a2.size)  # a2的数组元素个数: 9
print('a2的缓存区:', a2.data)  # a2的缓存区: <memory at 0x000001C8E9C958B8>
print('a2的元素类型:', a2.dtype)  # a2的元素类型: int32
print('a2的字节大小:', a2.itemsize)  # a2的字节大小: 4

创建数组

指定创建

函数方法 描述
np.empty(shape[, dtype, order]) 创建指定形状和dtype的未初始化数组
np.empty_like(prototype[, dtype, order, subok, …])
np.eye(N[, M, k, dtype, order]) 单位矩阵,N为行数,M为列数
np.diag() 对角矩阵
np.ones((shape[, dtype, order])) 创建指定形状的数组,数组元素以 1 来填充
np.ones_like(a[, dtype, order, subok, shape])
np.zeros((shape[, dtype, order])) 创建指定大小的数组,数组元素以 0 来填充
np.zeros_like(a[, dtype, order, subok, shape]))
np.full(shape, fill_value[, dtype, order]) 指定填充元素
np.full_like(a, fill_value[, dtype, order, …])
  • Dtype 所需的输出数组类型,可选
  • Order 'C'为按行的 C 风格数组,'F'为按列的 Fortran 风格数组
构造未初始的数组
numpy.empty(shape, dtype = float, order = 'C')
"""
shape      数组形状
dtype      数据类型,可选
order      有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。
"""
x = np.empty([3,2], dtype = int) 
print (x)
注释:此时输出的是随机数

创建0数值   
numpy.zeros(shape, dtype = float, order = 'C')
"""
shape     数组形状
dtype     数据类型,可选
order     'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组
"""

创建1数组
numpy.ones(shape, dtype = None, order = 'C')
"""
shape     数组形状
dtype     数据类型,可选  默认是浮点型    
order     'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组
"""

列表转数组
a = np.asarray([1,2,3],dtype)

将缓冲区data以流的形式读入转化成ndarray对象
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
"""
buffer     可以是任意对象,会以流的形式读入。
dtype     返回数组的数据类型,可选
count     读取的数据数量,默认为-1,读取所有数据。
offset     读取的起始位置,默认为0。
"""

numpy.fromiter(iterable, dtype, count=-1)
"""
iterable     可迭代对象
dtype     返回数组的数据类型
count     读取的数据数量,默认为-1,读取所有数据
"""

#----------------------------------------------------------
print(np.diag([1, 2, 3]))
#array([[1, 0, 0],
#         [0, 2, 0],
#         [0, 0, 3]])

print(np.diag([1, 2, 3], 1))
#array([[0, 1, 0, 0],
#        [0, 0, 2, 0],
#        [0, 0, 0, 3],
#        [0, 0, 0, 0]])
a = np.array([[1, 2], [3, 4]])
print(np.diag(a))
#array([1, 4])

从以有数据创建

函数方法 描述
numpy.array(object,dtype=None,copy=True,order=None,subok=False,ndmin=0)
numpy.asarray(a, dtype, order) 类似于numpy.array,可以将 Python 序列转换为ndarray
numpy.frombuffer(buffer, dtype, count, offset) 缓冲区data以流的形式读入转化成ndarray对象
numpy.fromiter(iterable, dtype, count=-1) 从可迭代对象中建立 ndarray 对象
numpy.asarray 类似 numpy.array,但 numpy.asarray  参数只有三个,比 numpy.array 少两个。
array和asarray都可以将结构数据转化为ndarray,
但是主要区别就是当数据源是ndarray时,array仍然会copy出一个副本,占用新的内存,但asarray不会。

创建数值范围

函数方法 描述
np.arange(start, stop, step, dtype) start 与 stop 指定的范围以及 step 设定的步长
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) 等差数组
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None) 等比数组
list=range(5)   #range 是可迭代对象而不是迭代器
it=iter(list) 
x=np.fromiter(it, dtype=float)

从数值范围创建并返回 ndarray对象
numpy.arange(start, stop, step, dtype)
"""
start     起始值,默认为0
stop     终止值(不包含)
step     步长,默认为1
dtype     返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型。
"""
x = np.arange(5)   # [0  1  2  3  4]

# 生成等差数列
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
"""
start         序列的起始值
stop         序列的终止值,如果endpoint为true,该值包含于数列中
num         要生成的等步长的样本数量,默认为50
endpoint     该值为 true 时,数列中包含stop值,反之不包含,默认是True。
retstep     如果为 True 时,生成的数组中会显示间距,反之不显示。
dtype         ndarray 的数据类型
"""

创建随机范围数据

np.random.random(size) 用于在区间[0,1)中生成均匀分布的随机数或随机数数组
np.random.rand(d0, d1, ..., dn) 生成服从均匀分布的随机数或随机数数组
np.random.randn(d0, d1, ..., dn) 生成服从正态分布的随机数或随机数数组
np.random.randint(low, high=None, size=None, dtype=int) 生成给定上下限范围的随机数

randint(low, high=None, size=None, dtype=int)

其中,参数low为最小值,high为最大值,size为数组维度,dtype为数据类型,默认的数据类型是np.int

import numpy as np

# 结果为一维数组
print('生成的随机数组为:',np.random.random(10))
生成的随机数组为:array([0.78283652, 0.9154314 , 0.41306707, 0.77055199, 0.16990905,
       0.07928419, 0.17580154, 0.5834303 , 0.52031781, 0.98319803])

# 结果为二维数组
print('生成的随机数组为:',np.random.random((2,5)))
生成的随机数组为:array([[0.97113777, 0.50128748, 0.76695156, 0.85181191, 0.25288016],
       [0.60372028, 0.67677372, 0.91640817, 0.61216549, 0.23824247]])


# 创建一维数组,元素个数为10,取值范围为[0,1)
arr1 = np.random.rand(10)

# 创建2行3列,取值范围为标准正态分布的数组
arr2 = np.random.randn(2,3)

print('生成的随机数组为:',np.random.randint(2,10,size = [2,5]))
生成的随机数组为: [[4 5 4 9 8]
 [2 7 2 3 2]]

posted @ 2021-07-15 09:20  贝壳里的星海  阅读(483)  评论(0编辑  收藏  举报