我正在尝试创建一个矩阵,该矩阵在我定义的函数的索引(i,j)处的值为f(i,j),。我正在尝试使用numpy.fromfunction进行此操作,但无法使其正常工作。这是代码

import numpy as np

def f(i,j):
    return sum((i+1)//k for k in np.arange(1,j+2))

def M(N):
    shape = np.array([N,N])
    np.fromfunction(f, shape,dtype = np.int)

A= M(5)


我得到错误


  Builtins.TypeError:只有长度为1的数组可以转换为Python标量


fromfunction的调用中,我想它必须与np.arange有关。

本来我有range(1,j+2)但后来我得到了错误


  TypeError:只能将整数标量数组转换为标量索引


你能告诉我我需要做什么吗?

最佳答案

我认为您必须先vectorize f

>>> np.fromfunction(np.vectorize(f), (5, 5), dtype=int)
array([[ 1,  1,  1,  1,  1],
       [ 2,  3,  3,  3,  3],
       [ 3,  4,  5,  5,  5],
       [ 4,  6,  7,  8,  8],
       [ 5,  7,  8,  9, 10]])


的确,fromfunction并非一次就传递坐标,而是一次传递:

>>> def f(i, j):
...     print(i, j)
...     return sum((i+1)//k for k in range(1, j+2))
...
>>> np.fromfunction(f, (5, 5), dtype=int)
[[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]] [[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]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/paul/local/lib/python3.6/site-packages/numpy/core/numeric.py", line 1914, in fromfunction
    return function(*args, **kwargs)
  File "<stdin>", line 3, in f
TypeError: only integer scalar arrays can be converted to a scalar index

关于python - 如何在numpy.fromfunction中使用范围?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49059667/

10-08 21:42