实验环境:建立在Python3的基础之上
numpy提供了一种数据类型,提供了数据分析的运算基础,安装方式
pip install numpy
导入numpy到python项目
import numpy as np
本文以案例的方式展示numpy的基本语法,没有介绍语法的细枝末节,笔者认为通过查阅案例就能掌握基本用法。
numpy数组的基本概念
numpy默认所有元素具有相同的数据类型,如果类型不一致,会对其进行优化。如果元素类型不同,将统一成一种类型,优先级:str>float>int
import numpy as np`` ``t_list = [1, 1.2, "hello"]``print(t_list)`` ``t_list = np.array([1, 1.2, "hello"])``print(t_list)`` ``t_list = np.array([1, 1.2])``print(t_list)
定义数组的时候,可以声明数据类型
t_list = np.array([1,2,3])``print(t_list)`` ``t_list = np.array([1,2,3], dtype=np.float32)``print(t_list)
numpy构造数组
1、np.ones(shape, dtype)
shape=(m,n) m行n列``shape=(m) m个元素的一维数组``shape=(m,) m个元素的一维数组``shape=(m,1) m行1列的二维数组 [[1],[2],[3]]``shape=(1,m) 1列m行的二维数组 [[1,2,3]]
t_list = np.ones(shape=(5,4), dtype=np.int32)``print(t_list)
2、np.zeros(shape, dtype)
t_list = np.zeros(shape=(5,3), dtype=np.int32)``print(t_list)
3、np.full(shape, fill_value, dtype)
t_list = np.full(shape=(2,3,4), fill_value=10, dtype=np.int32)``print(t_list)
4、np.eye(N,M,k,dtype)
# 单位矩阵``t_list = np.eye(N=5, dtype=np.float32)``print(t_list)`` ``# 控制行列的矩阵``t_list = np.eye(N=5, M=4, dtype=np.int32)``print(t_list)`` ``# 1向左偏移``t_list = np.eye(N=5, k=-1)`&