0

The code is as follows:

import numpy as np

def f(x):
    assert type(x) is np.ndarray
    return np.fromfunction(lambda i: np.sum(x[:i + 1]), (x.size,))


print(f(np.array((1, 2, 3))))

IndexError: failed to coerce slice entry of type numpy.ndarray to integer

I would expect the outcome to be [1, 1 + 2, 1 + 2 + 3] = [1, 3, 6]. If I change the return line of f to be:

return np.fromfunction(lambda i: np.sum(x[:int(i) + 1]), (x.size,))

I get:

TypeError: only length-1 arrays can be converted to Python scalars

I am simply mapping i to a constant and i should take the values 0, ..., x.size - 1 so I don't see whats wrong here.

th0masb
  • 303
  • 1
  • 11
  • 2
    Numpy does have a [cumulative sum](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.cumsum.html) – tiwo May 26 '17 at 23:26
  • Yes but its the concept behind it. I want to do it with a different function, not the sum but it still happens. Why is this not equivalent to the cumulative sum? – th0masb May 26 '17 at 23:29
  • 5
    `fromfunction()` calls your lambda function *once*, with argument `np.arange(x.size)`. That is, `i` will be an array, not a scalar. – Warren Weckesser May 26 '17 at 23:30
  • ah thank you!, I thought it repeatedly applied it to the indices. I wrote one like this and it worked but I forgot about vectorised operations. – th0masb May 26 '17 at 23:31
  • If you want to use a different function, consider `np.frompyfunc(...).accumulate` – Eric May 27 '17 at 00:26
  • So what you want is `np.array([np.sum(x[:i+1]) for i in range(len(x))])` – hpaulj May 27 '17 at 02:36
  • For source code and complaints about its documentation see https://stackoverflow.com/q/18702105. – hpaulj May 27 '17 at 10:51

0 Answers0