numpy函数fromfunction分析

本文介绍了如何使用numpy库中的fromfunction函数从函数规则创建数组,通过实例演示了shape参数的作用,展示了函数如何根据坐标计算数组元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    从函数规则创建数组是非常方便的方法。在numpy中我们常用fromfunction函数来实现这个功能。

    在numpy的官网有这么一个例子。

 1 >>> def f(x,y):
 2 ...         return 10*x+y
 3 ...
 4 >>> b = fromfunction(f,(5,4),dtype=int)
 5 >>> b
 6 array([[ 0,  1,  2,  3],
 7        [10, 11, 12, 13],
 8        [20, 21, 22, 23],
 9        [30, 31, 32, 33],
10        [40, 41, 42, 43]])

      查找help()解释如下:

  numpy.fromfunction(functionshape**kwargs)[source]

Construct an array by executing a function over each coordinate.

The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).

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. For example, if shape were (2, 2), then the parameters in turn be (0, 0), (0, 1), (1, 0), (1, 1).

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. By default, dtype is float.

Returns:

fromfunction : any

The result of the call to function is passed back directly. Therefore the shape of fromfunction is completely determined by function. If function returns a scalar value, the shape of fromfunction would match the shape parameter.

 

    主要是第二个参数shape,(N,)定义了fromfunction的输出数据形式。

    说起来比较绕口,下面用几个例子说明。

     

 1 # -*- coding: utf-8 -*-
 2 from numpy import *
 3 
 4 def f1(x,y):
 5     return x
 6 
 7 def f2(x,y):
 8     return y   
 9 
10 def f3(x,y):
11     return 2*x+y

  运行测试:

>>> b=fromfunction(f1, (5,5), dtype = int)
>>> b
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])

>>> b=fromfunction(f1, (5,4), dtype = int)
>>> b
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]])

>>> b=fromfunction(f2, (5,5), dtype = int)
>>> b
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
>>> b=fromfunction(f3, (5,5), dtype = int)
>>> b
array([[ 0, 1, 2, 3, 4],
[ 2, 3, 4, 5, 6],
[ 4, 5, 6, 7, 8],
[ 6, 7, 8, 9, 10],
[ 8, 9, 10, 11, 12]])
>>>

  从上面的测试可以看出,shape()定义了输出矩阵的大小。如shape(5,4),则x参数是5行1列行列式[0,1,2,3,4]. y参数1行4列行列式[0,1,2,3]. 

      将x,y带人func函数计算,最后结果的每个元素是根据func 函数来计算得出。

 

转载于:https://www.cnblogs.com/pingwen/p/4803501.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值