0%

NumPy的常用函数

numpy.full

  • numpy.full(shape, fill_value, dtype=None, order=’C’, **, like=None*)[source]

返回一个给定形状和类型的新数组,用fill_value填充。.

Parameters

shape:新矩阵的形状, e.g., (2, 3) or 2.

fill_value 填充的值

dtype 数据类型 None, meansnp.array(fill_value).dtype.

order{‘C’, ‘F’}, optionalWhether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.

like 可以从非NumPy转换, 前提是这个数组有 __array_function__ 属性

1
2
3
4
5
6
>>> np.full((2, 2), np.inf) 
array([[inf, inf], [inf, inf]])
>>> np.full((2, 2), 10)
array([[10, 10], [10, 10]])
>>> np.full((2, 2), [1, 2])
array([[1, 2], [1, 2]])

numpy.concatenate

  • numpy.concatenate((a1, a2, …), axis=0, out=None, dtype=None, casting=”same_kind”)

    将一系列array合起来

    **a1, a2, …array类型的数据

    相同的shape, except in the dimension corresponding to axis (the first, by default).

    axis int, optional

    按哪一个轴合到一起. 如果是None,array在操作前会被展平. 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.

    dtypestr or dtype

    If provided, the destination array will have this dtype. Cannot be provided together with out.

    New in version 1.20.0.

    casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

    Controls what kind of data casting may occur. Defaults to ‘same_kind’.

numpy.vstack

numpy.vstack(tup)[source]

按垂直方向将arrays合起来(按行)

类似于concat,将(N, )变成(1,N)

This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.

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). The functions concatenate, stack and block provide more general stacking and concatenation operations.

  • Parameters

    tupsequence of ndarraysThe arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

  • Returns

    stackedndarrayThe array formed by stacking the given arrays, will be at least 2-D.

numpy.argmax

取出一个轴上最大的值对应的索引

二维矩阵中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

import numpy as np
a = np.array([[1, 5, 5, 2],
[9, 6, 2, 8],
[3, 7, 9, 1]])
b=np.argmax(a, axis=0)#对二维矩阵来讲a[0][1]会有两个索引方向,第一个方向为a[0],默认按列方向搜索最大值
#a的第一列为1,9,3,最大值为9,所在位置为1,
#a的第一列为5,6,7,最大值为7,所在位置为2,
#此此类推,因为a有4列,所以得到的b为1行4列,
print(b)#[1 2 2 1]

c=np.argmax(a, axis=1)#现在按照a[0][1]中的a[1]方向,即行方向搜索最大值,
#a的第一行为1,5,5,2,最大值为5(虽然有2个5,但取第一个5所在的位置),索引值为1,
#a的第2行为9,6,2,8,最大值为9,索引值为0,
#因为a有3行,所以得到的c有3个值,即为1行3列
print(c)#[1 0 2]