【发布时间】:2013-09-09 15:47:02
【问题描述】:
我还没有理解numpy 中的关键概念。
我想创建一个 3 维数组并使用函数调用的结果填充每个单元格 - 即,该函数将使用不同的索引多次调用并返回不同的值。
注意:自从写了这个问题,文档已经更新得更清楚了。
我可以用零(或空)创建它,然后用 for 循环覆盖每个值,但直接从函数中填充它似乎更简洁。
fromfunction 听起来很完美。 Reading the documentation 听起来该函数每个单元格调用一次。
但是当我真正尝试它时......
from numpy import *
def sum_of_indices(x, y, z):
# What type are X, Y and Z ? Expect int or duck-type equivalent.
# Getting 3 individual arrays
print "Value of X is:"
print x
print "Type of X is:", type(x)
return x + y + z
a = fromfunction(sum_of_indices, (2, 2, 2))
我希望得到类似的东西:
Value of X is:
0
Type of X is: int
Value of X is:
1
Type of X is: int
重复 4 次。
我明白了:
Value of X is:
[[[ 0. 0.]
[ 0. 0.]]
[[ 1. 1.]
[ 1. 1.]]]
[[[ 0. 0.]
[ 1. 1.]]
[[ 0. 0.]
[ 1. 1.]]]
[[[ 0. 1.]
[ 0. 1.]]
[[ 0. 1.]
[ 0. 1.]]]
Type of X is: <type 'numpy.ndarray'>
该函数只被调用一次,并且似乎返回整个数组作为结果。
根据对索引函数的多次调用来填充数组的正确方法是什么?
【问题讨论】:
-
您的预期结果是什么?每个单元格调用一次 fromfunction - “多次调用索引函数”是什么意思?
-
在您的第一个代码块中,
a是您填充的数组,其中a[i, j, k] = sum_of_indices(i, j, k) -
对不起,我认为预期的结果从 cmets 很清楚。我已经扩展了。是的,我知道 'a' 是填充数组,但(我相信)只是因为数组添加。当我将 sum_of_indices 替换为无法实现的“真实”功能(例如数据库查找)时。