【NumPy】 之常见运算(np.around、np.floor、np.ceil、np.where)

around
np.around 返回四舍五入后的值,可指定精度。

around(a, decimals=0, out=None)

a 输入数组

decimals 要舍入的小数位数。 默认值为0。 如果为负,整数将四舍五入到小数点左侧的位置

·

# -*- coding: utf-8 -*-
"""
@author: tz_zs
"""
import numpy as np

n = np.array([-0.746, 4.6, 9.4, 7.447, 10.455, 11.555])

around1 = np.around(n)
print(around1) # [ -1. 5. 9. 7. 10. 12.]

around2 = np.around(n, decimals=1)
print(around2) # [ -0.7 4.6 9.4 7.4 10.5 11.6]

around3 = np.around(n, decimals=-1)
print(around3) # [ -0. 0. 10. 10. 10. 10.]
·

floor
np.floor 返回不大于输入参数的最大整数。 即对于输入值 x ,将返回最大的整数 i ,使得 i <= x。 注意在Python中,向下取整总是从 0 舍入。

·

# -*- coding: utf-8 -*-
"""
@author: tz_zs
"""
import numpy as np

n = np.array([-1.7, -2.5, -0.2, 0.6, 1.2, 2.7, 11])

floor = np.floor(n)
print(floor) # [ -2. -3. -1. 0. 1. 2. 11.]

·

ceil
np.ceil 函数返回输入值的上限,即对于输入 x ,返回最小的整数 i ,使得 i> = x。

# -*- coding: utf-8 -*-
"""
@author: tz_zs
"""
import numpy as np

n = np.array([-1.7, -2.5, -0.2, 0.6, 1.2, 2.7, 11])

ceil = np.ceil(n)
print(ceil) # [ -1. -2. -0. 1. 2. 3. 11.]
·

np.where
numpy.where(condition[, x, y])

根据 condition 从 x 和 y 中选择元素,当为 True 时,选 x,否则选 y。

https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

.

import numpy as np

data = np.random.random([2, 3])
print data
'''
[[ 0.93122679 0.82384876 0.28730977]
[ 0.43006042 0.73168913 0.02775572]]
'''

result = np.where(data > 0.5, data, 0)
print result
'''
[[ 0.93122679 0.82384876 0. ]
[ 0. 0.73168913 0. ]]
'''

猜你喜欢

转载自www.cnblogs.com/zknublx/p/11641942.html