Numpy库学习

Python学习

Python NumPy库的学习

这篇文章主要就是关于python第三方库Numpy的一些基础学习

NumPy的基础知识

开始前导入库并命名为np,同时设置随机数生成规则

import numpy as np
# 每次生成随机数相同
np.random.seed(seed=1234)
  • 对标量的创建
# 标量
x = np.array(8)
print("x=", x)
print("x ndim", x.ndim)
print("x shape", x.shape)
print("x size", x.size)
print("x dtype", x.dtype)
  • 一维数组的创建
# 一维数组
x = np.array([1.1, 2.2, 3.3])
print("x=", x)
print("x ndim", x.ndim)
print("x shape", x.shape)
print("x size", x.size)
print("x dtype", x.dtype)
  • 多维数组的创建
x = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
print("x=", x)
print("x ndim", x.ndim)
print("x shape", x.shape)
print("x size", x.size)
print("x dtype", x.dtype)

NumPy的函数

  • 上文函数
    上文中用到的ndim函数、shape函数、size函数、dtype函数是比较常用的几个函数,分别是矩阵的维度、长度、大小、数据类型,其中需要注意的是shape函数的使用。
    shape函数的功能是读取矩阵的长度,比如在二维中shape[0]就是读取矩阵第一维度的长度,相当于行数。它的输入参数可以是一个整数表示维度,也可以是一个矩阵。shape函数返回的是一个元组,表示数组(矩阵)的维度。
  • 标准矩阵生成函数
    这类函数主要用于生成如全零矩阵之类的特殊标准矩阵,用法与Matlab中相应矩阵的生成和使用方法一致。
# 函数
print(np.zeros((3, 3)))
print(np.ones((3, 3)))
print(np.eye((3, 3)))
print(np.random.random(3, 3))

NumPy的数学计算

  • 索引与切片
    Numpy中的索引与切片与List 的索引与切片基本一致,这里不再赘述
  • 维度相关
# 重复维度
x = np.array([[1, 2], [3, 4]])
y = np.array([5, 6])
add = np.tile(y, (len(x), 1))
print("add=", add)
z = x + add
print("z=", z)

# 广播
z = x + y
print("z=", z)

# 改变维度
x = np.array([[1, 2], [3, 4], [5, 6]])
print(x)
print("x.shape:", x.shape)
y = np.reshape(x, (2, 3))
print("y.shape", y.shape)
print("y=", y)
# 注意与转置的不同
print(x.T)
# 增删维度
x1 = np.array([[[1, 2, 3]], [[4, 5, 6]]])
print(x1)
print(x1.shape)
# 删除维度1
y = np.squeeze((x1, 1))
print(y)
print(y.shape)

x2 = np.array([[1, 2, 3],[4, 5, 6]])
print(x2)
print(x2.shape)
# 添加维度1
z = np.expand_dims(x2, 1)
print(z)
print(z.shape)

写在最后

上面主要是一些NumPy最基本操作,其他更加细致的操作看NumPy的官方库。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值