当前位置:网站首页>numpy库中的函数 bincount() where() diag() all()

numpy库中的函数 bincount() where() diag() all()

2022-08-09 10:28:00 白十月

毕设过程中遇到的,汇总在一起~

NumPy一元函数对ndarray中的数据执行元素级运算的函数

np.abs(x)、np.fabs(x) :

计算数组各元素的绝对值

np.sqrt(x) :

计算数组各元素的平方根

np.square(x) :

计算数组各元素的平方

np.log( )

以10为底 np.log10(x)
以e为底 np.log(x)

copy( )

numpy.bincount( )用法

输入数组x需要是非负整数,且是一维数组。
给出了它的索引值在x中出现的次数(在默认权重下)
本例中最大值是 6 ,因此显示的就是[0,6]这些数的次数
若不指定minlength,输出的个数应该为6+1=7

import numpy as np
x=np.array([1,2,3,3,0,1,4,0,6])
a = np.bincount(x)
print(a)

结果为:
[2 2 1 2 1 0 1]

增加参数 minlength
当minlength长度小于7时,输出不受影响;
但是,当minlength长度大于7时,其余位置会自动补0

import numpy as np
x=np.array([1,2,3,3,0,1,4,0,6])
a = np.bincount(x, minlength=20)
print(a)
结果为:
[2 2 1 2 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]

np.where( )用法

用法一 np.where(condition)
只有条件 (condition),没有x和y,则输出满足条件 (即非0) 元素的坐标 (等价于numpy.nonzero)。这里的坐标以tuple的形式给出,

import numpy as np
x=np.array([1,2,3,3,0,1,4,0,6])
a = np.where(x > 2)
print(a)
print(x[a])
结果为:
(array([2, 3, 6, 8], dtype=int64),)
[3 3 4 6]

用法二 np.where(condition, x, y)
满足条件(condition),输出x,不满足输出y

import numpy as np
x=np.array([1,2,3,3,0,1,4,0,6])
a = np.where(x > 2,1,0)
print(a)
结果为:
[0 0 1 1 0 0 1 0 1]

np.diag(array)

array是一个1维数组时,结果形成一个以一维数组为对角线元素的矩阵

array是一个二维矩阵时,结果输出矩阵的对角线元素

np.maximum(X, Y, out=None)

X和Y逐位进行比较,选择最大值.

numpy.all( )

numpy.all(a,axis = None,out = None,keepdims = <无值>)

测试是否沿给定轴的所有数组元素求值为True。
文档:
https://numpy.org/doc/1.17/reference/generated/numpy.all.html?highlight=numpy%20all#numpy.all

原网站

版权声明
本文为[白十月]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43251493/article/details/105930446