numpy.frompyfunc(func,nin,nout)函數允許創建一個任意的Python函數作為Numpy ufunc(通用函數)。
參數:
func: [A python function object ] An arbitrary python function
nin:[int] Number of input arguments to that function.
nout:[int] Number of objects returned by that function.返回: A Numpy universal function object.
例如,abs_value = numpy.frompyfunc(abs,1,1)將創建一個ufunc,該ufunc將返回數組元素的絕對值。
代碼1:
# Python code to demonstrate the
# use of numpy.frompyfunc
import numpy as np
# create an array of numners
a = np.array([34, 67, 89, 15, 33, 27])
# python str function as ufunc
string_generator = np.frompyfunc(str, 1, 1)
print("Original array-", a)
print("After conversion to string-", string_generator(a))
輸出:
Original array- [34 67 89 15 33 27] After conversion to string- ['34' '67' '89' '15' '33' '27']
代碼2:
# Python code to demonstrate
# user-defined function as ufunc
import numpy as np
# create an array of numbers
a = np.array([345, 122, 454, 232, 334, 56, 66])
# user-defined function to check
# whether a no. is palindrome or not
def fun(x):
s = str(x)
return s[::-1]== s
# 'check_palindrome' as universal function
check_palindrome = np.frompyfunc(fun, 1, 1)
print("Original array-", a)
print("Checking of number as palindrome-",
check_palindrome(a))
輸出:
Original array- [345 122 454 232 334 56 66] Checking of number as palindrome- [False False True True False False True]
注意:此自定義ufunc使用frompyfunc
始終接受ndarray作為輸入參數,並返回ndarray對象作為輸出。
相關用法
注:本文由純淨天空篩選整理自Tanvi_Garg大神的英文原創作品 numpy.frompyfunc() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。