一、多维数组
(一)NumPy(Numerical Python)
导入NumPy,import numpy as np
1、NumPy特点:
- 高性能科学计算和数据分析的基础包,提供多维数组对象
- ndarray,多维数组(矩阵),具有矢量运算能力,快速、节省空间
- 矩阵运算,无需循环,可完成类似Matlab中的矢量运算
- 线性代数、随机数生成
补充:
- SciPy,import scipy as sp
- 在NumPy库的基础上增加了众多的数学、科学及工程常用的库函数
- 线性代数、常微分方程求解、信号处理、图像处理、稀疏矩阵等
2、NumPy数据结构
ndarray,N维数组对象(矩阵)
- ndim属性,维度个数
- shape属性,各维度大小
- dtype属性,数据类型
![d0078c5d79df95298e06901bb8c83c1a.png](https://img-blog.csdnimg.cn/img_convert/d0078c5d79df95298e06901bb8c83c1a.png)
3、多维数组的创建
- np.array(collection),collection为序列型对象(list),嵌套序列(list of list)
l = [1,2,3,4,5,6]
data = np.array(l)
print(data)
print('维度个数:',data.ndim)
print('各维度大小:',data.shape)
print('数据类型:',data.dtype)
>>>[1 2 3 4 5 6]
维度个数:1
各维度大小:(6,)
数据类型:int32
- np.zeros(), np.ones() 指定大小的全0或全1数组
• 注意:第一个参数是元组,用来指定大小,如(3,4)
zeros_arr = np.zeros((2,3))
ones_arr = np.ones((2,2))
print(zeros_arr)
print(ones_arr)
>>>[[0. 0. 0.]
[0. 0. 0.]]
[[1. 1.]
[1. 1.]]
- np.random.rand(),生成指定形状的随机数组
rand_arr = np.random.rand(2,2)
print(rand_arr)
>>>[[0.03744583 0.77484823]
[0.18944974 0.76420786]]
- np.arange(),类似range函数,生成等差数组序列
arr = np.arange(10)
print(arr)
>>>[0 1 2 3 4 5 6 7 8 9]
- 转换形状,reshape()
- 转换数据类型,astype()
arr2 = arr.reshape((2,5))
print(arr2)
>>>[[0 1 2 3 4]
[5 6 7 8 9]]
print(arr2.dtype)
>>>int64
arr3 =