目录
基础
ndarray
用于存放同类型元素的多维数组。构造器:
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
# object:数组或嵌套的数列
# dtype:数据类型
# copy:对象是否需要复制
# order:创建数组的样式,C为行方向,F为列方向,A为任意方向(默认)
# subok:默认返回一个与基类类型一致的数组
# ndmin:指定生成数组的最小维度
举例:
# 导入numpy
import numpy as np
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
print(type(a))
# 把普通python中的list转换成ndarray
A = np.array(a)
print(A)
print(type(A))
# 直接创建一维数组
b = np.array([1, 2, 3, 4, 5])
print(b)
print(type(b))
# 创建多维数组
c = np.array([[1, 2, 3],[4, 5, 6]])
print(c)
print(type(c))
print(c.ndim) # 打印维度
d = np.array([[[1,2,3],[4,5,6],[7,8,9]]])
print(d)
print(d.ndim)
# 指定维度创建多维数组
e = np.array([1, 2, 3, 4, 5, 6], ndmin = 3, dtype = np.float32)
print(e)
# 指定detype参数
f = np.array([1, 2, 3, 4, 5, 6], dtype = np.complex)
print(f)
数据类型
数据类型对象(dtype),构造语法:
numpy.dtype(object, align, copy)
# Object: 被转换为数据类型的对象
# Align:如果为true,则向字段添加间隔,使其类似C的结构体
# Copy:生成dtype对象的新副本,如果为false,结果是内建数据类型对象的引用
基础数据类型:
import numpy as np
# 声明一个dtype类型对象
dt = np.dtype(np.int32)
print(dt)
# 如何使用上面创建的dt对象
a = np.array([1, 2, 3, 4, 5, 6], dtype = dt)
print(a)
# 声明一个float类型的dtype
dt_f = np.dtype(np.float32)
b = np.array([1, 2, 3, 4, 5, 6], dtype = dt_f)
print(b)
# 声明一个复数类型的dtype
dt_c = np.dtype(np.complex)
c = np.array([1, 2, 3, 4, 5, 6], dtype = dt_c)
自定义数据类型:
import numpy as np
# 使用dtype创建自定义化结构类型
dt_struct = np.dtype([("age", np.int32)])
a = np.array([(10,),(20,),(30,)],dtype = dt_struct)
print(a)
print(a['age'])
# 利用dtype创建自定义实体对象类型
dt_person = np.dtype([("name","S20"),("age",np.int32)])
b = np.array([("bruce",30),("andy",25)])
print(b)
数组属性
- ndarray.shape:形状
- ndarray.ndim:维度
- ndarray.itemsize:字节长度
在 NumPy中,每一个线性的数组称为是一个轴(axis),也就是维度(dimensions)。比如说,二维数组相当于是两个一维数组,其中第一个一维数组中每个元素又是一个一维数组。所以一维数组就是 NumPy 中的轴(axis),第一个轴相当于是底层数组,第二个轴是底层数组里的数组。而轴的数量——秩,就是数组的维数。
很多时候可以声明 axis。axis=0,表示沿着第 0 轴进行操作,即对每一列进行操作;axis=1,表示沿着第1轴进行操作,即对每一行进行操作。
import numpy as np
# ndarray.shape以元组的形式返回数组的形状/大小
a = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
print(a)
print(a.shape)
# 通过shape改变数组的形状
a.shape = (4,2)
print(a)
# ndarray中的ndim
b = np.array([1, 2, 3, 4, 5, 6])
print(b.ndim)
# 通过reshape改变维度
c = b.reshape(2,1,3)
print(c)
print(c.ndim)
# ndarray.itemsize返回数组中每个元素单位字节长度
x = np.array([[1, 2, 3, 4, 5],[6, 7, 8, 9, 10]], dtype = np.float64)
print(x.itemsize)
创建数组
除了使用底层 ndarray 构造器创建,也可以通过以下几种方式来创建:
import numpy as np
# numpy.empty以为初始化的方式创建数组
a = np.empty([3,2], dtype = np.int32)
print(a)
# numpy.zeros返回制定大小的数组,并且以0作为填充
b = np.zeros([5,6], dtype = np.int32)
print(b)
# numpy.zeros_like/numpy.empty_like模仿一个数组,创建以0填充空数组
c = np.array([[1, 2, 3],[4, 5, 6]])
print(c)
d = np.zeros_like(c)
print(d)
f = np.empty_like(c)
print(f)
# numpy.ones返回指定数组大小的数组,并且以1来填充
g = np.ones([3,2], dtype = np.float32)
print(g)
h = np.array([[1, 2, 3, 4, 5],[6, 7, 8, 9, 10]],dtype = np.float32)
i = np.ones_like(h)
print(i)
# numpy.eye返回对角线为1,其余为0
j = np.eye(5,dtype = np.float32)
print(j)
# numpy.asarray把python中的list和元组转换成ndarray
k = [1, 2, 3, 4, 5, 6]
# k = (1, 2, 3, 4, 5, 6)
l = np.asarray(k)
print(type(k))
print(type(l))
print(k)
print(l)
# numpy.arange返回给定范围的数组
m = np.arange(10, 20, 3, dtype = np.int32)
print(type(m))
print(m)
n = np.arange(10, dtype = np.int32)
print(n)
# numpy.linspace返回指定范围内的均匀间隔
o = np.linspace(10, 20, 6)
print(o)
o = np.linspace(10, 20)
print(o)
进阶
切片与索引
ndarray对象的内容可以通过索引护着切片来访问和修改。三种可用的索引方法类型:字段访问,基本切片和高级索引。
import numpy as np
a = np.arange(10)
print(a)
# slice函数有三个参数,第一个star表示起始位置,第二个stop表示结束位置,第三个表示步长
s = slice(2, 10, 2)
print(a[s])
# 直接使用
b = a[2:10:2]
print(b)
# 对单个元素进行切片
print(a[5])
# 从开始进行切片
c = a[2:]
print(c)
# 指定开始和结束位置进行切片
d = a[4:8]
print(d)
# 整数索引
x = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(x)
# 目标:取出(0,0)(1,1)(2,0)位置的元素
y = x[[0,1,2],[0,1,0]]
print(y)
x = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]])
print(x)
# 目标:取出四个角的元素
rows = np.array([[0, 0],[3, 3]])
clos = np.array([[0, 3],[0, 3]])
y = x[rows,clos]
print(y)
# 布尔索引
x = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(x)
# 取出大于5的元素
y = x[x > 5]
print(y)
# 取出小于5的元素
print(x[x < 5])
数组广播
广播是指numpy在算术运算期间处理不同形状的数组的能力。numpy可以通过广播对形状不想死的数组进行操作。较小的数组会广播到较大数组的大小,以便它们的形状可兼容。
import numpy as np
# 同维矩阵操作
a = np.array([1, 2, 3, 4, 5])
b = np.array([10, 20, 30, 40, 50])
print(a + b)
print(a * b)
print(b - a)
# 不同维矩阵操作,需要使用广播
a = np.array([[1, 1, 1],[10, 10, 10],[20, 20, 20]])
b = np.array([1, 2, 3])
print(a)
print(b)
print(a + b)
print(a - b)
数组操作
反转操作
import numpy as np
# reshape操作
a = np.arange(10)
print(a)
b = a.reshape(2, 5)
print(b)
c = a.reshape(5, 2)
print(c)
# flat操作
a = np.arange(10).reshape(2, 5)
print(a)
print(a.flat[:])
print(a.flat[6])
# flatten操作
print(a.flatten())
# T操作
print(a)
print(a.T)
链接操作
import numpy as np
# concatenate操作
a = np.arange(6).reshape(2, 3)
print(a)
b = np.array([[7, 8, 9],[10, 11, 12]])
print(b)
print("沿着0轴进行链接")
print(np.concatenate((a, b)))
print("沿着1轴进行链接")
print(np.concatenate((a, b), axis = 1))
# stack操作
a = np.array([[1, 2, 3],[4, 5, 6]])
b = np.array([[7, 8, 9],[10, 11, 12]])
print(a)
print(b)
print("沿着0轴进行堆叠")
print(np.stack((a, b), 0))
print("沿着1轴进行堆叠")
print(np.stack((a, b), 1))
# hstack水平方向
a = np.array([[1, 2],[3, 4]])
b = np.array([[5, 6],[7, 8]])
print(a)
print(b)
print("水平堆叠")
print(np.hstack((a, b)))
print("竖直堆叠")
print(np.vstack((a, b)))
分割操作
import numpy as np
# 分割操作
# split操作
a = np.arange(12)
print(a)
print("将数组a分割成大小相等的三个子数组")
b = np.split(a, 3)
print(b)
print("数组中明确位置进行分割")
c = np.split(a, [4, 7])
print(c)
# hsplit操作
a = np.arange(16).reshape(4, 4)
print(a)
b = np.hsplit(a, 2)
print(b)
# vsplit操作
c = np.vsplit(a, 2)
print(c)
其他操作
import numpy as np
# resize操作
a = np.array([[1, 2, 3],[4, 5, 6]])
print(a)
print(a.shape)
print(np.resize(a, (3, 2)))
# append操作
a = np.arange(10).reshape(2, 5)
print(a)
print(np.append(a, [10, 11, 12]))
print("沿着0轴进行添加")
print(np.append(a, [[10, 11, 12, 13, 14]], axis = 0))
print("沿着1轴进行添加")
print(np.append(a, [[6, 6, 6],[7, 7, 7]], axis = 1))
# insert操作
a = np.array([[1, 2],[3, 4],[5, 6]])
print(a)
print("未传入axis参数,插入时会展开成一维数组")
print(np.insert(a, 6, [8, 9]))
print("沿着0轴进行添加")
print(np.insert(a, 1, [8, 9], axis = 0))
print("沿着1轴进行添加")
print(np.insert(a, 1, [8, 9, 10], axis = 1))
# delete操作
a = np.arange(12).reshape(3, 4)
print(a)
print("未传入axis参数,删除时会展开成一维数组")
print(np.delete(a, 6))
print("传入axis = 0参数,将按行删除")
print(np.delete(a, 2, axis = 0))
print("传入axis = 1参数,将按列删除")
print(np.delete(a, 2, axis = 1))
# unique操作
a = np.array([1, 2, 3, 4, 5, 5, 5, 5, 6, 6, 6, 7, 8, 9, 9, 9])
print(a)
print("调用unique函数进行对重复元素的删除")
print(np.unique(a))
字符串操作
import numpy as np
# numpy.char.add操作:执行字符串链接操作
a = "hello"
b = "bruce"
c = np.char.add(a, b)
print(c)
a = ["hello", "hi"]
b = ["bruce", "andy"]
c = np.char.add(a, b)
print(c)
# numpy.char.multiply操作
a = "hello"
b = np.char.multiply(a, 5)
print(b)
# numpy.char.center操作
a = "hello"
b = np.char.center(a, 30, fillchar = "*")
print(b)
# numpy.char.capitalize操作
a = "hello bruce"
b = np.char.capitalize(a)
print(b)
# numpy.char.title操作
a = "hello bruce"
b = np.char.title(a)
print(b)
# numpy.char.lower操作
a = "HELLO BRUCE"
b = np.char.lower(a)
print(b)
# numpy.char.upper操作
a = "hello bruce"
b = np.char.upper(a)
print(b)
# numpy.char.split操作
a = "hello#how#are#you"
b = np.char.split(a, "#")
print(b)
# numpy.char.splitlines操作
a = "hello\nhow \nare you"
b = np.char.splitlines(a)
print(b)
# numpy.char.strip操作
a = "bhello brucea"
b = np.char.strip(a, "b")
print(b)
# numpy.char.join操作
a = "hello"
b = np.char.join("-", a)
print(b)
# numpy.char.replace操作
a = "He is a good boy"
b = np.char.replace(a, "is", "was")
print(b)
# numpy.char.encode操作
a = "您好"
b = np.char.encode(a, "gbk")
print(a)
print(b)
c = np.char.decode(b, "gbk")
print(c)
高级
三角函数
import numpy as np
# numpy.sin
a = np.array([0, 30, 45, 60, 90])
print(np.sin(a * np.pi / 180))
# numpy.cos
a = np.array([0, 30, 45, 60, 90])
print(np.cos(a * np.pi / 180))
# numpy.tan
a = np.array([0, 30, 45, 60, 90])
print(np.tan(a * np.pi / 180))
反三角函数
import numpy as np
# numpy.arcsin
a = np.array([0, 30, 45, 60, 90])
sin = np.sin(a * np.pi / 180)
print(sin)
inv = np.arcsin(sin)
print(inv)
print(np.degrees(inv))
# numpy.arccos
a = np.array([0, 30, 45, 60, 90])
cos = np.cos(a * np.pi / 180)
print(cos)
inv = np.arccos(cos)
print(inv)
print(np.degrees(inv))
# numpy.arctan
a = np.array([0, 30, 45, 60, 90])
tan = np.tan(a * np.pi / 180)
print(tan)
inv = np.arctan(tan)
print(inv)
print(np.degrees(inv))
舍入函数
import numpy as np
# numpy.floor:向下取整
a = np.array([-1.8, 1.6, -0.3, 0.5, 10.0])
print(a)
b = np.floor(a)
print(b)
# numpy.ceil:向上取整
c = np.ceil(a)
print(c)
运算
加减乘除
import numpy as np
# add
a = np.arange(16, dtype = np.int32).reshape(4, 4)
print(a)
b = np.array([20, 20, 20, 20])
print(b)
print(np.add(a, b))
# subtract
print(np.subtract(a, b))
# multiply
print(np.multiply(a, b))
# divide
print(np.divide(a, b))
reciprocal、power与mod
import numpy as np
# reciprocal
a = np.array([0.5, 1.55, 1, 0.1, 100])
print(a)
print(np.reciprocal(a))
# power
a = np.array([2, 3, 4])
print(a)
print(np.power(a, 2))
c = np.array([1, 2, 3])
print(np.power(a, c))
# mod
a = np.array([10, 20, 30])
print(a)
b = np.array([3, 5, 7])
print(b)
print(np.mod(a, b))
复数运算
import numpy as np
# numpy.real
a = np.array([-7.8j, 0.5j, 11, 5 + 5j])
print(a)
print(np.real(a))
# numpy.imag
a = np.array([-7.8j, 0.5j, 11, 5 + 5j])
print(a)
print(np.imag(a))
# numpy.conj
a = np.array([-7.8j, 0.5j, 11, 5 + 5j])
print(a)
print(np.conj(a))
# numpy.angle
a = np.array([-7.8j, 0.5j, 11, 5 + 5j])
print(a)
print(np.angle(a))
print(np.angle(a, deg = True))
统计函数
amin、amax与ptp
import numpy as np
# amin
a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(a)
print("调用amin函数打印纵向")
print(np.amin(a, 1))
print("调用amin函数打印横向")
print(np.amin(a, 0))
# amax
print("调用amin函数打印纵向")
print(np.amax(a, 1))
print("调用amin函数打印横向")
print(np.amax(a, 0))
# ptp:函数计算数组中元素最大值与最小值的差(最大值 - 最小值)
print("调用ptp")
print(np.ptp(a))
print("沿着1轴调用ptp")
print(np.ptp(a, axis = 1))
print("沿着0轴调用ptp")
print(np.ptp(a, axis = 0))
median、mean与average
import numpy as np
# median
a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print("调用median函数")
print(np.median(a))
print("沿着0轴方向调用median函数")
print(np.median(a, axis = 0))
print("沿着1轴方向调用median函数")
print(np.median(a, axis = 1))
# mean
a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print("调用mean函数")
print(np.mean(a))
print("沿着0轴方向调用mean函数")
print(np.mean(a, axis = 0))
print("沿着1轴方向调用mean函数")
print(np.mean(a, axis = 1))
# average
a = np.array([1, 2, 3, 4])
print(a)
print("调用average函数")
print(np.average(a))
wts = np.array([4, 3, 2, 1])
print("加入权重调用average函数")
c = np.average(a, weights = wts)
print(c)
标准差与方差
import numpy as np
# 标准差std
a = np.array([1, 2, 3, 4])
print(a)
print("使用std计算标准差")
print(np.std(a))
# 方差var
print(np.var(a))
sort、argmax与argmin
import numpy as np
# sort
a = np.array([[6, 5], [8, 9]])
print(a)
print(np.sort(a))
# argmax
a = np.array([[1, 2, 3],[4, 10, 6],[7, 8, 9]])
print(a)
print(np.argmax(a))
print("沿着0轴方向进行argmax")
print(np.argmax(a, axis = 0))
print("沿着1轴方向进行argmax")
print(np.argmax(a, axis = 1))
# argmin
a = np.array([[1, 2, 3],[4, 10, 6],[7, 8, 9]])
print(a)
print(np.argmin(a))
print("沿着0轴方向进行argmin")
print(np.argmin(a, axis = 0))
print("沿着1轴方向进行argmin")
print(np.argmin(a, axis = 1))
where和extract
import numpy as np
# where:返回满足条件元素的索引
x = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(x)
print("返回大于5的元素的索引")
y = np.where(x > 5)
print(y)
print("使用索引取出元素")
print(x[y])
# extract:返回满足条件元素
# 定义一个条件
condition = np.mod(x, 2) == 0
print(condition)
print("获取满足条件的元素")
print(np.extract(condition, x))
矩阵库
import numpy as np
import numpy.matlib
# numpy.matlib.zeros()
a = np.matlib.zeros((5, 6))
print(a)
# numpy.matlib.identity()
a = np.matlib.identity(5)
print(a)
# numpy.matlib.rand()
a = np.matlib.rand((6, 7))
print(a)
线性代数
数组点积
import numpy as np
# dot操作
a = np.array([[3, 4],[5, 6]])
b = np.array([[13, 14],[15, 16]])
print(a)
print(b)
c= np.dot(a, b)
print(c)
矩阵点积
import numpy as np
# numpy.vdot
a = np.array([[3, 4],[5, 6]])
b = np.array([[13, 14],[15, 16]])
print(a)
print(b)
print(np.vdot(a, b))
数组内积
import numpy as np
# numpy.inner
a = np.array([[1, 2],[3, 4]])
b = np.array([[5, 6],[7, 8]])
print(a)
print(b)
print(np.inner(a, b))
数组的矩阵积
import numpy as np