工作中使用numpy是遇到了一下几个函数,写一篇笔记记录一下以防以后忘记。
- np.linspace创建等差数列
np.linspace(start, stop, num=50, endpoint=True,restep=False, dtype=None)
start:起始值
stop:终止值
num: 值的个数,默认50
endpoint: True包含终止值,否则不包含终止值
retstep: True则返回样本值和步长
dtype:返回的数组类型
return sample: 数组
step:步长
print(np.linspace(2.0, 3.0, num = 5)) # [2. 2.25 2.5 2.75 3. ]
print(np.linspace(2.0, 3.0, num=5, endpoint=False)) # [2. 2.2 2.4 2.6 2.8]
print(np.linspace(2.0, 3.0, num=5, retstep=True)) # (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
n = 8
xx1 = np.linspace(0, 10, n, endpoint=True)
xx2 = np.linspace(0, 10, n, endpoint=False)
print(xx1,xx2)
yy = np.zeros(n)
plt.plot(xx1, yy, "o")
plt.plot(xx2, yy+0.5, 'o')
plt.ylim([-0.5,1])
plt.show()
- np.logspace创建等比数列
np.logspace(start, stop, num=50, endpoint=True, base=10.0,dtype=None)
start: basestart 是序列的开始值
stop: basestop 是序列的最后一个值
num: 需要生成的值得个数,默认是50
endpoint: TRUE: 包含最后一个值。否则不包含最后一个值
base: 底数,默认是10
dtype: 输出数组的类型
return:数组
print(np.logspace(2.0, 3.0, num=4)) # [ 100. 215.443469 464.15888336 1000. ]
print(np.logspace(2.0, 3.0, num=4, endpoint=False)) # [100. 177.827941 316.22776602 562.34132519]
print(np.logspace(2.0, 3.0, num=4, base=2)) # [4. 5.0396842 6.34960421 8. ]
N = 10
x1 = np.logspace(0.1,1, N,endpoint=True)
x2 = np.logspace(0.1,1, N, endpoint=False)
y = np.zeros(N)
plt.plot(x1, y, "o")
plt.plot(x2, y+0.5, 'o')
plt.ylim([-0.5,1])
plt.savefig("plt2.png")
plt.show()
- math.ceil()执行向上舍入,即总是将数值向上舍入为最接近的整数,返回 x 的上限,即大于或者等于 x 的最小整数
math.floor()执行向下舍入,即总是将数值向下舍入为最接近的整数
round() 执行标准舍入,四舍五入
print(math.ceil(1.1111)) # 2
print(math.floor(1.1111)) # 1
print(round(1.1111)) # 1
print(math.ceil(1.99)) # 2
print(math.floor(1.99)) # 1
print(round(1.99)) # 2
- np.unique()去除数组中重复数字,并进行排序后输出
np.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
ar: 输入的原始数组
return_index: 默认False,True返回排序之后的该数在原来数组中的索引下标
return_inverse:默认False,True返回该数所在原数组的下标
print(np.unique([1, 277, 77, 2, 2, 77, 0],return_index=True)) # (array([ 0, 1, 2, 77, 277]), array([6, 0, 3, 2, 1], dtype=int64))
u, indices = np.unique([1, 277, 77, 2, 2, 77, 0],return_inverse=True)
print(u, indices) # (array([ 0, 1, 2, 77, 277]), array([1, 4, 3, 2, 2, 3, 0], dtype=int64))
print(u[indices]) # 重构原数组 [ 1 277 77 2 2 77 0]