numpy中的相关函数的讲解_eye_identity_ones_like_power_cumsum_cumprod_linspace_logspace_diag_floor_log

1、np.eye()和np.identity()

import numpy as np

# 只创建一个方阵
a = np.identity(3)
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]
print(a)

a = np.eye(3)
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]
print(a)

a = np.eye(4, k=1)
# [[0. 1. 0. 0.]
#  [0. 0. 1. 0.]
#  [0. 0. 0. 1.]
#  [0. 0. 0. 0.]]
print(a)

a = np.eye(4, k=-1)
# [[0. 0. 0. 0.]
#  [1. 0. 0. 0.]
#  [0. 1. 0. 0.]
#  [0. 0. 1. 0.]]
print(a)

a = np.eye(4, k=-3)
# [[0. 0. 0. 0.]
#  [0. 0. 0. 0.]
#  [0. 0. 0. 0.]
#  [1. 0. 0. 0.]]
print(a)

2、np.ones_like

  返回与输入数据的形状和类型 一致的全1数组,通过dtype=np.float将int类型的数字1变成浮点型1.。
1、代码

x = np.arange(6, dtype=np.float).reshape((2, 3))
# [[0. 1. 2.]
#  [3. 4. 5.]]
print(x)
y = np.ones_like(x)
# [[1. 1. 1.]
#  [1. 1. 1.]]
print(y)

3、np.power

  power(x, y) 函数,返回x 的 y 次方。
1、代码

# 8
print(np.power(2, 3))

4、np.cumsum()

  按顺序连加,保留上一次的加法值,请看下面的关于axis=0的三种情况:

a = np.array([[1, 2, 3], [4, 5, 6]])
# [ 1  3  6 10 15 21]
print(np.cumsum(a))
# 垂直方向上进行按行连加,第一次[1 2 3],第二次为[1 2 3]+[4, 5, 6]=[5 7 9]
# [[1 2 3]
#  [5 7 9]]
print(np.cumsum(a, axis=0))
# 水平方向上进行按行连加,第一次1,4不动,第二次为(1,4)+(2,5)=(3,9)
# [[ 1  3  6]
#  [ 4  9 15]]
print(np.cumsum(a, axis=1))

5、np.cumprod()

  按顺序连乘,保留上一次的乘法值。在泰勒公式中,有使用到该函数。
1、代码

# 通过累乘来得到当前的数据
# [  1   2   6  24 120]
y1 = np.arange(1, 6).cumprod()
print(y1)

print("--------------------")
x = [2]
# [[2], [2]]
print(([x] * 2))
# [2 4]
b = np.array([x] * 2).cumprod()
print(b)

# 其他更一般的情况
a = np.array([[1, 2, 3], [4, 5, 6]])
# [  1   2   6  24 120 720]
print(np.cumprod(a))
# 垂直方向上进行按行连加,第一次[1 2 3],第二次为[1 2 3]*[4, 5, 6]=[4 10 18]
# [[ 1  2  3]
#  [ 4 10 18]]
print(np.cumprod(a, axis=0))
# 水平方向上进行按行连加,第一次1,4不动,第二次为(1,4)*(2,5)=(2,20)
# [[  1   2   6]
#  [  4  20 120]]
print(np.cumprod(a, axis=1))

6、np.linspace

  在指定的间隔内(start, stop),返回固定间隔(等差数组)的数据。

linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

  下面代码表示生成数据的三种情况:
1、代码

# 包含stop点
x1 = np.linspace(1, 5, 5)
# 去掉stop点
x2 = np.linspace(1, 5, 5, endpoint=False)
# 省略生成元素的个数,默认会生成50个数据
x3 = np.linspace(1, 5)
# [1. 2. 3. 4. 5.]
print(x1)
# [1.  1.8 2.6 3.4 4.2]
print(x2)
# [1.         1.08163265 1.16326531 1.24489796 1.32653061 1.40816327
#  1.48979592 1.57142857 1.65306122 1.73469388 1.81632653 1.89795918
#  1.97959184 2.06122449 2.14285714 2.2244898  2.30612245 2.3877551
#  2.46938776 2.55102041 2.63265306 2.71428571 2.79591837 2.87755102
#  2.95918367 3.04081633 3.12244898 3.20408163 3.28571429 3.36734694
#  3.44897959 3.53061224 3.6122449  3.69387755 3.7755102  3.85714286
#  3.93877551 4.02040816 4.10204082 4.18367347 4.26530612 4.34693878
#  4.42857143 4.51020408 4.59183673 4.67346939 4.75510204 4.83673469
#  4.91836735 5.        ]
print(x3)

7、np.logspace()

  创建不同底的等比数列。
1、代码

# 以2为底
a1 = np.logspace(0, 9, 10, base=2)
# 起始值为10^0,终止值为10^9,有10个数的等比数列
a2 = np.logspace(0, 9, 10)
# [  1.   2.   4.   8.  16.  32.  64. 128. 256. 512.]
print(a1)
# [1.e+00 1.e+01 1.e+02 1.e+03 1.e+04 1.e+05 1.e+06 1.e+07 1.e+08 1.e+09]
print(a2)

8、np.diag()

  该函数用于生成对角矩阵或者获得矩阵中对角的元素,从而构成一个向量。
1、代码

# (array([[1., 0.],
#        [0., 1.]]), array([[3, 0],
#        [0, 3]]), array([[2, 0],
#        [0, 5]]), array([[2, 1],
#        [2, 5]]))
sigma = (np.identity(2), np.diag((3, 3)), np.diag((2, 5)), np.array(((2, 1), (2, 5))))
x1 = np.array([[1, 2], [3, 4]])
x2 = np.diag(x1)
x3 = np.diag((2, 5))
print(sigma)
# 对于已经生成的矩阵,返回对角线上的元素
# [1 4]
print(x2)
# 对于未生成的矩阵,返回一个对角矩阵
# [[2 0]
#  [0 5]]
print(x3)

9、np.floor()数据取整操作

  对于数值数据的取整操作。
1、代码

# 情况1: 向下取整 1.0
print(np.floor(1.23))

# 情况2:对数据四舍五入(取整数)
c = 1.2
a = int(c + 0.5)

# 情况3和4
n = np.array([-2.7, 2.7, 4.3])
# 向上取整,与四舍五入无关
# [-2.  3.  5.]
print(np.ceil(n))
# 四舍五入取整
# [-3.  3.  4.]
print(np.rint(n))

10、np.log()

  对数不同底的三种情况介绍。
1、代码

# 以e为底,输出0.9999999998311266
print(np.log(2.718281828))
# 以2为底,输出1
print(np.log2(2))
# 以10为底,输出1
print(np.log10(10))

11、np.fromstring()

  该函数可以从字符串解码出ASCII码或者从字符串中进行解码出数据。
1、代码

# 从字符串解码出ASCII码
s = 'abcdz'
g1 = np.fromstring(s, dtype=np.int8)
# [ 97  98  99 100 122]
print(g1)
# 从字符串中进行解码出数据
g2 = np.fromstring('1 2 3', dtype=int, sep=' ')
# [1 2 3]
print(g2)
你可以使用 Python 的内置函数 `dir()` 来查看一个库(模块)中所有的函数和变量。例如,如果你想查看 NumPy中的所有函数和变量,可以在 Python 中输入以下代码: ```python import numpy as np print(dir(np)) ``` 这将会打印出 NumPy 库中所有的函数和变量名称,如下所示: ``` ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'absolute', 'absolute_import', 'add', 'alen', 'all', 'allclose', 'alltrue', 'alterdot', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal', 'array_equiv', 'array_repr', 'array_split', 'array_str', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'beta', 'binary_repr', 'bincount', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'block', 'bmat', 'bool', 'bool8', 'broadcast', 'broadcast_arrays', 'broadcast_to', 'busday_count', 'busday_offset', 'busdaycalendar', 'byte', 'bytes', 'bytes0', 'bytes_', 'c_', 'can_cast', 'cast', 'cbrt', 'cdouble', 'ceil', 'chararray', 'choose', 'clip', 'column_stack', 'common_type', 'compare_chararrays', 'compat', 'complex', 'complex128', 'complex64', 'complex_', 'compress', 'concatenate', 'conjugate', 'contains', 'convolve', 'copy', 'core', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov', 'cross', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum', 'datetime64', 'datetime_as_string', 'deg2rad', 'degrees', 'delete', 'deprecate', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide', 'dot', 'double', 'dsplit', 'dstack', 'dtype', 'dump', 'dumps', 'ediff1d', 'einsum', 'elect', 'element_wise', 'empty', 'empty_like', 'equal', 'errstate', 'exp', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 'fft', 'fill_diagonal', 'find_common_type', 'finfo', 'fix', 'flat', 'flatiter', 'flatten', 'fliplr', 'flipud', 'float', 'float128', 'float16', 'float32', 'float64', 'float_', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_float_positional', 'format_float_scientific', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full', 'full_like', 'fv', 'gcd', 'generic', 'genfromtxt', 'get_array_wrap', 'get_include', 'get_numarray_include', 'get_printoptions', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'gradient', 'greater', 'greater_equal', 'hamming', 'hanning', 'heaviside', 'histogram', 'histogram2d', 'histogram_bin_edges', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'ifft', 'imag', 'in1d', 'index_exp', 'indices', 'inf', 'info', 'inner', 'insert', 'int', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'integer', 'interp', 'intersect1d', 'intersect1d_nu', 'intp', 'invert', 'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'iterable', 'ix_', 'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'lib', 'linalg', 'linspace', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'lstsq', 'ma', 'mafromtxt', 'mask_indices', 'mat', 'math', 'matmul', 'matrix', 'max', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min', 'minimum', 'mintypecode', 'mirr', 'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 'nanquantile', 'nanstd', 'nansum', 'nanvar', 'nanwarnings', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'negative', 'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'np', 'numarray', 'number', 'obj2sctype', 'object', 'object0', 'object_', 'ogrid', 'oldnumeric', 'ones', 'ones_like', 'outer', 'packbits', 'pad', 'partition', 'percentile', 'pi', 'piecewise', 'pinv', 'place', 'pmt', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'ppmt', 'print_function', 'product', 'promote_types', 'ptp', 'put', 'put_along_axis', 'putmask', 'pv', 'quantile', 'r_', 'rad2deg', 'radians', 'random', 'rank', 'rate', 'ravel', 'real', 'real_if_close', 'recarray', 'reciprocal', 'record', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 'safe_eval', 'save', 'savetxt', 'savez', 'savez_compressed', 'sctype2char', 'sctypeDict', 'sctypeNA', 'sctypes', 'searchsorted', 'select', 'set_numeric_ops', 'set_printoptions', 'set_string_function', 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setxor1d', 'shape', 'shares_memory', 'show_config', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'sinh', 'size', 'slice', 'solve', 'sort', 'sort_complex', 'source', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'str', 'str0', 'str_', 'subtract', 'sum', 'svd', 'swapaxes', 'sys', 'take', 'take_along_axis', 'tan', 'tanh', 'tensordot', 'test', 'testing', 'tile', 'timedelta64', 'trace', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'typeDict', 'typeNA', 'typename', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'union1d', 'unique', 'unique1d', 'unpackbits', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'version', 'void', 'void0', 'vsplit', 'vstack', 'warnings', 'weibull', 'where', 'who', 'zeros', 'zeros_like'] ``` 注意,`dir()` 会输出所有名称,包括 Python 内置函数、变量和 NumPy 模块中的名称。如果你只想查看 NumPy 模块中的名称,你可以使用 `dir(np.core)`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值