【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. ]]
'''


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM