数据小站
数据科学成长之路

numpy内置函数

import numpy as np

文中“np” 约定俗成的代表了numpy缩写

1 np.empty_like() 复制一个与目标数组相同shape和类型的空数组

类似empty_like 的有 one_like, zeros_like ,full_like , empty 。使用方式一致,区别在于返回的数据默认值。

def empty_like(prototype, dtype=None, order=None, subok=None, shape=None):
    """
    empty_like(prototype, dtype=None, order='K', subok=True, shape=None)

    Return a new array with the same shape and type as a given array.

    Parameters
    ----------
>>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> np.empty_like(a)
array([[ -2.00000715e+000,   1.48219694e-323,  -2.00000572e+000], # uninitialized
       [  4.38791518e-305,  -2.00000715e+000,   4.17269252e-309]])

高级属性,empty_like() 除了必填的参数, 还有用于控制数组中数据在内存中的C/F顺序方式。

2 np.concatenate() 数组拼接合并

def concatenate(arrays, axis=None, out=None):
    """
    concatenate((a1, a2, ...), axis=0, out=None)

    Join a sequence of arrays along an existing axis.

    Parameters
    ----------
    a1, a2, ... : sequence of array_like
        The arrays must have the same shape, except in the dimension
        corresponding to `axis` (the first, by default).
    axis : int, optional
        The axis along which the arrays will be joined.  If axis is None,
        arrays are flattened before use.  Default is 0.
    out : ndarray, optional
        If provided, the destination to place the result. The shape must be
        correct, matching that of what concatenate would have returned if no
        out argument were specified.

    Returns
    -------
    res : ndarray
        The concatenated array.

按轴方向将数组合并拼接。

官网示例

Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
       [3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])

axis设置数组合并的轴向拼接方式, 是沿x轴还是y轴进行拼接。默认axis=None时,将所有数据拉伸城一维度进行拼接。

3 np.inner() 数组内积

文档定义函数:
def inner(a, b):
    """
    inner(a, b)

    Inner product of two arrays.

    Ordinary inner product of vectors for 1-D arrays (without complex
    conjugation), in higher dimensions a sum product over the last axes.

    Parameters
    ----------

实现方式

Notes
-----
For vectors (1-D arrays) it computes the ordinary inner-product::

    np.inner(a, b) = sum(a[:]*b[:])

More generally, if `ndim(a) = r > 0` and `ndim(b) = s > 0`::

    np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))

np.inner()计算两个数组的内积,看文档标注的实现原理。当两个数组为1-D一维数组时,inner()计算的是对应元素乘积之和。

当两个数组高于1维时,通用的做法是通过np.tensordot()函数实现了计算,相当于是tensordot()函数的一个快捷计算方式。

inner()直观的理解是, 两个数组,按行,每个对应的元素乘积之和,放在对应位置上。 和np.dot() 计算逻辑刚好相反。

4 np.dot() 数组乘积

np.dot() 实现线性代数中常用的矩阵乘积的场景。

np.dot() 和 np.inner()区别

np.dot()实现的是 矩阵的乘积, 是线下代数中的一个常用的场景。

np.dot()和np.inner()最直观的区别在于 两个数组在对应元素相乘上,取值的逻辑刚好为相对于的两个场景:

np.dot(a, b ) 是将 a ,b 两个数组乘积, a中各行对应元素, 与 b中各列对应元素, 点乘求和后 放到 新数组对应a行b列的位置上。

np.inner(a, b ) 是将 a ,b 两个数组乘积, a中各行对应元素, 与 b中各行对应元素, 点乘求和后 放到 新数组对应a行b行的位置上。

5 np.where()

np.where() 是一个比较高级的实用性很强的函数。

def where(condition, x=None, y=None):
    """
    where(condition, [x, y])

    Return elements chosen from `x` or `y` depending on `condition`.

矢量级的数组判断,根据condition的true 和 false, 返回对应 x 和y 值。

官网文档示例 
Examples
--------
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(a < 5, a, 10*a)
array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

当np.where() 参数只传condition 条件, x 和 y 为none时,此时返回的是一个序列, 序列记录了 condition条件下为真实对应的位置。

6 np.lexsort() 序列多键值排序

def lexsort(keys, axis=None):
"""
lexsort(keys, axis=-1)

Perform an indirect stable sort using a sequence of keys.

示例

>>> a = [1,5,1,4,3,4,4]
>>> b = [9,4,0,4,0,2,1]
>>> ind = np.lexsort((b,a)) # Sort by a, then by b
>>> ind
array([2, 0, 4, 6, 5, 3, 1])

>>> [(a[i],b[i]) for i in ind]
[(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]

np.lexsort((b,a))多键的排序,先按最后一个key a排序, 当a值相同时,在按照b键排序,返回的是一个根据排序的位置序列,序列记录了每个位置的值在数组中的索引位置。

类似sql中 order by key_a, key_b 用法。

7 np.bincount() 计算1维数组中每个非负整数出现的次数

定义函数
def bincount(x, weights=None, minlength=None):
    """
    bincount(x, weights=None, minlength=0)
    Count number of occurrences of each value in array of non-negative ints.
...
 Parameters
    ----------
    x : array_like, 1 dimension, nonnegative ints
        Input array.
    weights : array_like, optional
        Weights, array of the same shape as `x`.
    minlength : int, optional
        A minimum number of bins for the output array.

        .. versionadded:: 1.6.0

    Returns
    -------
    out : ndarray of ints
        The result of binning the input array.
        The length of `out` is equal to ``np.amax(x)+1``.
示例:
>>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1])

使用说明:

bincount() 函数返回序列的长度 , 为 bincount(a) 参数a中 最大值+ 1 (The length of `out` is equal to “np.amax(x)+1“.)

bincount()参数要求是1维整数。返回结果是统计输入数组中,每个非负整数出现的次数。 返回值的序列为从0 到最大值+1, 用于分别记录每个输入数组中每个值出现的次数。

有个weights权重参数可选,使用时长度和输入数组保存一致,计算次数时值对应的权重叠加统计。

8 np.putmask()

Changes elements of an array based on conditional and input values.

根据条件改变数组中的值,可以用np.where()替换实现。

9 np.shares_memory() 查看两个数组是否共享内存

Examples
--------
>>> x = np.array([1, 2, 3, 4])
>>> np.shares_memory(x, np.array([5, 6, 7]))
False
>>> np.shares_memory(x[::2], x)
True
>>> np.shares_memory(x[::2], x[1::2])
False

10 np.may_share_memory() 查看两个数组可能来自同一个内存数组

Examples
    --------
    >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
    False
    >>> x = np.zeros([3, 4])
    >>> np.may_share_memory(x[:,0], x[:,1])
    True

11 np.take() 选取数组中的指定位置数据

Examples
--------
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])

12 np.reshape() 重塑数组shape

Examples
--------
>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])
>>> np.reshape(a, 6, order='F')
array([1, 4, 2, 5, 3, 6])

>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
[3, 4],
[5, 6]])

重塑shape时,指定一个轴为-1时,则根据另一个轴的维度自适应。

13 基础函数集合

np.average()

np.gradient()

返回一组数据的梯度

赞(0) 打赏
未经允许不得转载:技术文档分享 » numpy内置函数

评论 抢沙发