[Python] Numpy Learning

Python 中提供了 list 容器,可以当作数组使用。但列表中的元素可以是任何对象,因此列表中保存的是对象的指针,这样一来,为了保存一个简单的列表 [1,2,3]。就需要三个指针和三个整数对象。对于数值运算来说,这种结构显然不够高效。

构建数组

直接从 list 中构建

array 中的参数是数组的数据

x = np.array([2, 3, 4])
x = np.array([[2, 3, 4], [5, 6, 7]])
x = np.array([2, 3, 4], dtype=np.uint8)
x = np.array([2, 3, 4], dtype=np.uint8)

empty, zeros, ones

empty 可以构建形状为 shape 的数组,其值取决于内存原始值。zeros,ones 可以将内存初始化

x = np.empty(shape=100, dtype=np.uint8)
x = np.empty(shape=(10, 10))
x = np.empty(shape=(10, 10), dtype=np.uint16)
x = np.zeros(shape=(10, 10))
x = np.ones(shape=(10, 10))

random

randint 可以构建形状为 size 的数组,其值为 [low, high) 的随机整数

x = np.random.randint(5)
x = np.random.randint(low=2, high=10, size=5)
x = np.random.randint(low=2, high=10, size=(3, 4))

randn 从标准正太分布中返回数值

x = np.random.randn(5, 5)

rand 从 [0, 1) 中随机选择

x = np.random.rand(5, 5)

选择数组元素

...

...: 用来快速操作 numpy

x = np.random.randn(3, 3, 2)

x[..., 1] 表示前两维保持不变,最后一维取 1 号元素,变成 3*3 矩阵,效果等同于 x[:, :, 1]
x[1, ...] 表示第一维取 1 号元素,其余维度保持不变,变成 3*2 矩阵,效果等同于 x[1, :, :]x[1]
x[1, ..., 1] 表示第一维和最后一维取 1 号元素,其余维度保持不变,变成 3 维矩阵,效果等同于 x[1, :, 1]

list

使用 list 操作 array,返回值依旧是 array

x = np.random.randn(10, 5)
a = [1, 3, 5]
x[a]
x[a, :]
x[:, a]
x[..., a]

数组拓展维度

打开 ipython

x = np.random.randn(5)
x.shape # (5,)
y = np.expand_dims(x, axis=0)
y.shape # (1,5)
y = np.expand_dims(x, axis=-1)
y.shape # (5,1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值