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


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


numpy.fromfunction()函数通过在每个坐标上执行一个函数来构造一个数组,因此,所得数组在坐标(x,y,z)处的值为fn(x,y,z)。

Syntax:numpy.fromfunction(function, shape,  dtype)

Parameters:

function:[callable] The function is called with N parameters, where N is the rank of shape. Each parameter represents the coordinates of the array varying along a specific axis.

shape:[(N, ) tuple of ints] Shape of the output array, which also determines the shape of the coordinate arrays passed to function.



dtype:[data-type, optional] Data-type of the coordinate arrays passed to function.

Return:The output array.

代码1:

Python3

# Python program explaining 
# numpy.fromfunction() function 
    
# importing numpy as geek 
import numpy as geek 
    
gfg = geek.fromfunction(lambda i, j:i * j, (4, 4), dtype = float) 
    
print(gfg)

输出:

[[0. 0. 0. 0.]

[0. 1. 2. 3.]

[0. 2. 4. 6.]

[0. 3. 6. 9.]]

代码2:

Python3

# Python program explaining 
# numpy.fromfunction() function 
    
# importing numpy as geek 
import numpy as geek 
    
gfg = geek.fromfunction(lambda i, j:i == j, (3, 3), dtype = int) 
    
print(gfg)

输出:

[[ True False False]

[False True False]

[False False True]]

相关用法


注:本文由纯净天空筛选整理自sanjoy_62大神的英文原创作品 numpy.fromfunction() function – Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。