当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python numpy.frompyfunc()用法及代码示例


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。