Numpy

2022-03-06  本文已影响0人  QXPLUS

NumPy ( Numerical Python)是支持 Python 语言的数值计算扩充库,其拥有强大的多维数组处理与矩阵运算能力

NumPy 是 Scipy.org 中最重要的库之一,它同时也被 Pandas,Matplotlib 等我们熟知的第三方库作为核心计算库。当你在单独安装这些库时,你会发现同时会安装 NumPy 作为依赖

数值类型 dtype(data-type) 对象的实例

import numpy as np
a = np.array([1.1,2.2,3.3],
             dtype = np.float64)
print(a.dtype)
#  dtype('float64')
a.astype(int)
# array([1, 2, 3])
a.astype(int).dtype
# dtype('int64')

NumPy 数组生成

NumPy 中,多维数组对象ndarray 具有六个参数:

在 NumPy 中,我们主要通过以下 5 种途径创建数组:

1. 从 Python 数组结构列表,元组等转换

numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
其中,参数:
object:列表、元组等。
dtype:数据类型。如果未给出,则类型为被保存对象所需的最小类型。
copy:布尔类型,默认 True,表示复制对象。
order:顺序。
subok:布尔类型,表示子类是否被传递。
ndmin:生成的数组应具有的最小维数。

2. 使用 np.arangenp.onesnp.zeros 等 NumPy 原生方法。
3. 从已知数据创建

我们还可以从已知数据文件、函数中创建 ndarray。

数组基本操作

reshape 可以在不改变数组数据的同时,改变数组的形状。其中,numpy.reshape() 等效于 ndarray.reshape()reshape 方法非常简单:

numpy.reshape(a, newshape)

数组展开

ravel 的目的是将任意形状的数组扁平化,变为 1 维数组。

numpy.ravel(a, order='C')

轴移动

moveaxis 可以将数组的轴移动到新的位置。

a.shape, np.moveaxis(a, 0, -1).shape
(1, 2, 3), (2, 3, 1)

轴交换

swapaxes 可以用来交换数组的轴。

numpy.swapaxes(a, axis1, axis2)

a.shape, np.swapaxes(a,0,2).shape
(1, 4, 3), (3, 4, 1)

维度改变

atleast_xd 支持将输入数据直接视为 x维。这里的 x 可以表示:1,2,3

numpy.atleast_1d()
numpy.atleast_2d()
numpy.atleast_3d()

np.atleast_1d([1,2,3]).shape, np.atleast_2d([1,2,3]).shape,np.atleast_3d([1,2,3]).shape
(3,), (1, 3), (1, 3, 1)

类型转换

在 NumPy 中,还有一系列以 as 开头的方法,它们可以将特定输入转换为数组,亦可将数组转换为矩阵、标量,ndarray 等。

数组连接

concatenate 可以将多个数组沿指定轴连接在一起。
numpy.concatenate((a1, a2, ...), axis=0)

数组堆叠
拆分
追加
搜索和计数
  1. extract(condition,arr):返回满足某些条件的数组的元素。
上一篇 下一篇

猜你喜欢

热点阅读