numpy函数fromfunction分析
从函数规则创建数组是非常方便的方法。在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(function, shape, **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
shape : (N,) tuple of ints
dtype : data-type, optional
|
---|---|
Returns: |
fromfunction : any
|
主要是第二个参数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 函数来计算得出。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 2025成都.NET开发者Connect圆满结束