【numpy】使用笔记
笔记。
参考:
NumPy是使用Python进行科学计算的基础软件包。包括:1)功能强大的N维数组对象。2)精密广播功能函数。3)集成C/C+和Fortran代码的工具。4)强大的线性代数、傅立叶变换和随机数功能。
- NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。ndarray 对象是用于存放同类型元素的多维数组。ndarray 中的每个元素在内存中都有相同存储大小的区域。
- ndarray对象的内容可以通过索引或切片来访问和修改,与 Python 中 list 的切片操作一样。ndarray 数组可以基于 0 - n 的下标进行索引,切片对象可以通过内置的 slice 函数,并设置 start, stop 及 step 参数进行,从原数组中切割出一个新数组。
import numpy as np
定义
np.mat()、np.matrix()、np.array()函数解析(最清晰的解释)
np.mat()函数用于将输入解释为矩阵。
np.matrix()函数用于从类数组对象或数据字符串返回矩阵。
np.array()函数用于创建一个数组。
统计
np.mean
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)
沿着指定的维度(若有指定,否则展平所有元素)计算-算术平均值。算术平均值是沿着轴的元素之和除以元素个数。
Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.
axis
: None or int or tuple of ints, optional. Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.
np.std
numpy.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)
Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.
数据拼接
np.column_stack(tup)
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack
. 1-D arrays are turned into 2-D columns first.
- [Parameters]:
tup
, sequence of 1-D or 2-D arrays. Arrays to stack. All of them must have the same first dimension.- [Returns]:
stacked
, 2-D array. The array formed by stacking the given arrays.
np.hstack(tup)
tup
: sequence of ndarrays.
Stack arrays in sequence horizontally (column wise).
This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.
This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis).
Similarly,
np.vstack(tup)
: Stack arrays in sequence vertically (row wise).
np.vstack(tup)用法类似【Stack arrays in sequence vertically (row wise)】。
np.concatenate().
numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")
Join a sequence of arrays along an existing axis.
The axis along which the arrays will be joined. If axis
is None, arrays are flattened before use. Default is 0.
文件
.txt读写
np.savetxt('data/task.txt', self.task, fmt="%d", delimiter=" ")
data/task.txt:参数为文件路径以及TXT文本名
self.task: 为要保存的数组名
fmt="%d": 为指定保存的文件格式,这里为十进制
delimiter=" "表示分隔符,这里以空格的形式隔开
np.loadtxt(fname):将数据读出为array类型,fname表示需要加载的文件名及其路径
Tips
UserWarning: loaded more than 1 DLL from .libs: 【参考:numpy版本问题】