NumPy

文章目录

  • 前言
    • NumPy安装
    • 知识准备
  • ndarray属性
  • ndarray创建
  • ndarray变换
    • 维度变换
    • 元素类型变换
    • 转换为list
    • 多个数组堆叠
    • 拆分为小数组
  • ndarray索引
  • ndarray切片
  • ndarray迭代
  • ndarray运算
    • 一元函数
    • 二元函数

前言

此篇是NumPy的快速入门指南,将了解到n维数组的表示与其相关操作。

NumPy安装

原安装路径较慢,可使用以下镜像

清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
阿里云 http://mirrors.aliyun.com/pypi/simple/

安装numpy

pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple

安装matplotlib

pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple 

知识准备

python教程

Numpy的主要对象是同构多维数组。同构多维数组是一个由相同类型元素组成,由非负整数元祖索引的元素表。通常其元素类型为number。

Numpy的维度称为轴。

#如下为三维空间一个点的坐标数组。其具有1个轴,长度为3
[1,2,3]

#如下数组,其有2个轴,第1个轴长度为2,第二个轴长度为3
[[1,2,3],
 [4,5,6]]

NumPy数组类称为ndarray,别称array。


ndarray属性

属性 返回类型 返回值 备注
ndarray.ndim int 数组的轴数 即数组的维度数量
ndarray.shape tuple 数组的维度 元祖的每个元素对应着每个维度的数组大小
ndarray.size int 数组的元素总数 即ndarray.shape返回值元组中所有元素的乘积
ndarray.dtype object 数组中元素的类型 可以使用标准的Python类型创建或指定dtype
ndarray.itemsize int 数组中每个元素的大小 以字节为单位
import numpy as np
a = np.array([[0, 1, 2, 3, 4],
             [5, 6, 7, 8, 9],
             [10, 11, 12, 13, 14]])
print(type(a)) # 
print(a.ndim) # 2
print(a.shape) # (3,5)
print(a.size) # 15
print(a.dtype) # int32
print(a.itemsize) # 4

ndarray创建

1.从其他Python结构(list,tuple)转换

函数 说明
np.array(list/tuple,dtype) 不指定dtype时,ndarray的dtype由创建序列元素的类型推导而来
import numpy as np

#list创建,不指定dtype
a = np.array([[0, 1, 2],
             [3, 4, 5]])
print(a) 
#[[0 1 2]
# [3 4 5]]

#tuple创建,不指定dtype
b = np.array([(0, 1, 2), (3, 4, 5)])
print(b) 
#[[0 1 2]
# [3 4 5]]
print(b.dtype) # int32

#指定dtype
c = np.array([(0, 1, 2), (3, 4, 5)], dtype=float)
print(c) 
#[[0. 1. 2.]
# [3. 4. 5.]]
print(c.dtype) # float64

2.numpy原生数组的创建

以下函数均可传入dtype指定返回数组中的元素类型,不传入则根据情况自动推导

函数 说明
np.arrage(start,end,step) 创建start到end-1,步长为step的一维数组。start与step均可省略
np.ones(shape) 创建元素全为1的数组,维度由shape元组决定
np.ones_like(a) 创建元素全为1的数组,维度与数组a相同
np.zero(shape) 创建元素全为0的数组,维度由shape元组决定
np.zero_like(a) 创建元素全为0的数组,维度与数组a相同
np.full(shape,val) 创建元素全为val的数组,维度由shape元组决定
np.full_like(a,val) 创建元素全为val的数组,维度与数组a相同
np.eye(n) 创建一个n*n的矩阵数组,对角线元素为1,其余值为0
np.linspace(start,end,num) 创建start到end,元素个数为num,步长相等的一维数组
np.concatenate((a,b)) 创建由数组a和b拼接成的新数组
import numpy as np

a = np.arange(1, 20, 2)
print(a) # [ 1  3  5  7  9 11 13 15 17 19]

b = np.ones((3, 2))
print(b)
#[[1. 1.]
# [1. 1.]
# [1. 1.]]

c=np.ones_like([[1,2,3],[4,5,6]])
print(c)
#[[1 1 1]
# [1 1 1]]

d = np.zeros((3, 2))
print(d)
#[[0. 0.]
# [0. 0.]
# [0. 0.]]

e = np.zeros_like([[1, 2, 3], [4, 5, 6]])
print(e)
#[[0 0 0]
# [0 0 0]]

f = np.full((3, 2),5)
print(f)
#[[5 5]
# [5 5]
# [5 5]]

g = np.full_like([[1, 2, 3], [4, 5, 6]],5)
print(g)
#[[5 5 5]
# [5 5 5]]

h = np.eye(3)
print(h)
#[[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]

i = np.linspace(1, 9, 5)
print(i) # [1. 3. 5. 7. 9.]

j = np.concatenate((g, h))
print(j)
#[[5. 5. 5.]
# [5. 5. 5.]
# [1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]

ndarray变换

维度变换

函数 说明 原数组影响
a.reshape(shape) 返回新数组,其维度由shape元组决定,可设置其中一个值为-1以自动计算 不修改原数组
a.resize(shape) 修改原数组维度,由shape元组决定 修改原数组
a.swapaxex(ax1,ax2) 返回新数组,调换原数组中的ax1和ax2两个维度 不修改原数组
a.flatten() 数组降维,返回一维数组 不修改原数组
import numpy as np
a = np.arange(1, 20, 2)
print(a) #[ 1  3  5  7  9 11 13 15 17 19]

b=a.reshape(2,-1)
print(a) #[ 1  3  5  7  9 11 13 15 17 19]
print(b)
#[[ 1  3  5  7  9]
# [11 13 15 17 19]]

c=a.resize(2,5)
print(a)
#[[ 1  3  5  7  9]
# [11 13 15 17 19]]
print(c) #None

d = a.swapaxes(0, 1)
print(a)
#[[ 1  3  5  7  9]
# [11 13 15 17 19]]
print(d)
#[[ 1 11]
# [ 3 13]
# [ 5 15]
# [ 7 17]
# [ 9 19]]

e=a.flatten()
print(a)
#[[ 1  3  5  7  9]
# [11 13 15 17 19]]
print(e)
#[ 1  3  5  7  9 11 13 15 17 19]

元素类型变换

函数 说明 原数组影响
a.astype(dtype) 返回新数组,其元素类型为dtype 不修改原数组
import numpy as np
a = np.arange(1, 20, 2)
print(a) #[ 1  3  5  7  9 11 13 15 17 19]

b = a.astype(float)
print(a) #[ 1  3  5  7  9 11 13 15 17 19]
print(b) #[ 1.  3.  5.  7.  9. 11. 13. 15. 17. 19.]

转换为list

函数 说明 原数组影响
a.tolist() 返回list 不修改原数组
import numpy as np
a = np.arange(1, 20, 2)
print(a) #[ 1  3  5  7  9 11 13 15 17 19]

b = a.tolist()
print(a) #[ 1  3  5  7  9 11 13 15 17 19]
print(b) #[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

多个数组堆叠

以下函数均返回新数组,不修改原数组

函数 说明
np.vstack((a,b)) 垂直(行)按顺序堆叠数组
np.hstack((a,b)) 水平(按列)顺序堆叠数组
np.column_stack(a,b) 列堆叠,将一维数组作为列堆叠到二维数组中
np.dstack((a,b)) 沿深度方向(沿第三轴)按顺序堆叠数组
import numpy as np
#一维数组的堆叠
a = np.arange(4)
print(a) #[0 1 2 3]
b = np.arange(6, 10)
print(b) #[6 7 8 9]

print(np.vstack((a, b)))
#[[0 1 2 3]
# [6 7 8 9]]

print(np.dstack((a, b)))
#[[[0 6]
#  [1 7]
#  [2 8]
#  [3 9]]]

print(np.hstack((a, b)))
#[0 1 2 3 6 7 8 9]

print(np.column_stack((a, b)))
#[[0 6]
# [1 7]
# [2 8]
# [3 9]]

#二维数组的堆叠
c = a.reshape(2,2)
print(c)
#[[0 1]
# [2 3]]
d = b.reshape(2,2)
print(d)
#[[6 7]
# [8 9]]

print(np.vstack((c, d)))
#[[0 1]
# [2 3]
# [6 7]
# [8 9]]
print(np.dstack((c, d)))
#[[[0 6]
#  [1 7]]

# [[2 8]
#  [3 9]]]
print(np.hstack((c, d)))
#[[0 1 6 7]
# [2 3 8 9]]
print(np.column_stack((c, d)))
#[[0 1 6 7]
# [2 3 8 9]]

拆分为小数组

函数 说明
vsplit(ary, indices_or_sections) 垂直(行)将数组拆分为多个子数组
hsplit(ary, indices_or_sections) 水平(按列)将一个数组拆分为多个子数组
dsplit(ary, indices_or_sections) 沿第3轴(深度)将数组拆分为多个子数组
import numpy as np
a = np.arange(12).reshape(6, -1)
print(a)
#[[ 0  1]
# [ 2  3]
# [ 4  5]
# [ 6  7]
# [ 8  9]
# [10 11]]

b = np.vsplit(a, 3)
print(b)
#[array([[0, 1],
#       [2, 3]]), array([[4, 5],
#       [6, 7]]), array([[ 8,  9],
#       [10, 11]])]

c = np.vsplit(a, (2,5))
print(c)
#[array([[0, 1],
#       [2, 3]]), array([[4, 5],
#       [6, 7],
#       [8, 9]]), array([[10, 11]])]
import numpy as np
a = np.arange(12).reshape(2, -1)
print(a)
#[[ 0  1  2  3  4  5]
# [ 6  7  8  9 10 11]]

b = np.hsplit(a, 3)
print(b)
#[array([[0, 1],
#       [6, 7]]), array([[2, 3],
#       [8, 9]]), array([[ 4,  5],
#       [10, 11]])]

c = np.hsplit(a, (2,5))
print(c)
#[array([[0, 1],
#       [6, 7]]), array([[ 2,  3,  4],
#       [ 8,  9, 10]]), array([[ 5],
#       [11]])]

import numpy as np
a = np.arange(12).reshape(3, 2, 2)
print(a)
#[[[ 0  1]
#  [ 2  3]]

# [[ 4  5]
#  [ 6  7]]

# [[ 8  9]
#  [10 11]]]

b = np.dsplit(a, 2)
print(b)
#[array([[[ 0],
#        [ 2]],
#
#       [[ 4],
#        [ 6]],
#
#       [[ 8],
#        [10]]]), array([[[ 1],
#        [ 3]],
#
#       [[ 5],
#        [ 7]],
#
#       [[ 9],
#        [11]]])]

ndarray索引

索引:获取数组中特定位置元素

索引方式 说明
a[index1,index2,…] index为每个维度的索引位置
import numpy as np

#一维数组索引
a = np.arange(12)
print(a) #[ 0  1  2  3  4  5  6  7  8  9 10 11]
b = a[2] 
print(b) # 2

#多维数组索引
a.resize(2, 2, 3)
print(a)
#[[[ 0  1  2]
#  [ 3  4  5]]

# [[ 6  7  8]
#  [ 9 10 11]]]
c = a[1, 1, 1]
print(c) # 10

ndarray切片

切片:获取数组元素子集

切片方式 说明
a[start1:end1:step1,start2:end2:step2] 每个维度返回start到end-1的数组元素,步长为step。其中start缺省为0,end缺省为a的最大索引位置,step缺省为1
import numpy as np

#一维数组切片
a = np.arange(12)
print(a) #[ 0  1  2  3  4  5  6  7  8  9 10 11]
b = a[2:6:2] 
print(b) #[2 4]

#多维数组切片
a.resize(2, 2, 3)
print(a)
#[[[ 0  1  2]
#  [ 3  4  5]]

# [[ 6  7  8]
#  [ 9 10 11]]]
c = a[:1:, :, :2]
print(c)
#[[[0 1]
#  [3 4]]]

ndarray迭代

迭代:遍历数组,并进行相应操作

import numpy as np
a = np.arange(6).reshape(2, 3)
print(a)
#[[0 1 2]
# [3 4 5]]

#迭代每一行
for row in a:
    print(row)
#[0 1 2]
#[3 4 5]

迭代每一个元素
for el in a.flat:
    print(el)
#0
#1
#2
#3
#4
#5

ndarray运算

注意:ndarry中的运算是元素级的,且不会修改原数组

一元函数

函数 说明
np.abs(a)
np.fabs(a)
计算各元素的绝对值
返回新数组
np.sqrt(a)
np.square(a)
np.exp(a)
计算各元素的平方根、平方、指数
返回新数组
np.mean(a)
np.average(a)
np.median
返回所有元素的平均值,加权平均值,中位数
np.prod(a)
返回所有元素乘积
np.var(a)
np.std(a)
返回所有元素的方差、标准方差
np.sort 对所有元素进行排序
返回新数组
np.log(a)
np.log10(a)
np.log2(a)
计算各元素自然对数、10底对数、2底对数
返回新数组
np.ceil(a)
np.floor(a)
np.rint(a)
对各元素进行向上取值、向下取整、四舍五入
返回新数组
np.sign(a) 计算各元素的符号值
返回新数组
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a)
#[[ 0  1  2  3]
# [ 4  5  6  7]
# [ 8  9 10 11]]

b = np.mean(a)
print(b) # 5.5

c = np.square(a)
print(c)
#[[  0   1   4   9]
# [ 16  25  36  49]
# [ 64  81 100 121]]

d = np.sign(a)
print(d)
#[[0 1 1 1]
# [1 1 1 1]
# [1 1 1 1]]

二元函数

函数 说明
a+b
a-b
a*b
a/b
两个数组对应各元素分别进行计算
返回新数组
a@b 数组进行矩阵乘法计算
返回新数组
np.mod(a,b) 两个数组对应各元素取模
返回新数组
np.maximum(a,b) np.fmax(a,b)
np.minimum(a,b) np.fmin(a,b)
取对应位置较大/小的元素
返回新数组
np.copysign(a,b) 将b数组各元素的符号赋值给a数组对应各元素
返回新数组
a>b
aa>=b
a<=b
a==b
a!=b
两个数组对应各元素进行比较
返回布尔值数组
import numpy as np
a = np.arange(6).reshape(2, 3)
print(a)
#[[0 1 2]
# [3 4 5]]

b = np.arange(6).reshape(3, 2)
print(b)
#[[0 1]
# [2 3]
# [4 5]]

c = np.arange(3, 9).reshape(2, 3)
print(c)
#[[3 4 5]
# [6 7 8]]

d = a@b
print(d)
#[[10 13]
# [28 40]]

e = a+c
print(e)
#[[ 3  5  7]
# [ 9 11 13]]

f = np.maximum(a, c)
print(f)
#[[3 4 5]
# [6 7 8]]

参考:
https://numpy.org/devdocs/user/quickstart.html
https://www.pianshen.com/article/31901301376

你可能感兴趣的:(Python相关,python)