If you can please provide context about the need for such a function I am happy to adjust my response but given your function I was able to simply the code to the following.
def docal2(a: np.array, b: np.array, d: np.array) -> np.array:
r, c = a.shape
sum_ = np.zeros(c, dtype=float)
for i in range(r):
sum_[0:d[i]] -= a[i, 0]
sum_[d[i]] += b[i, 0]
print(f"{sum_=}")
return sum_
This should prevent unecessay slicing of your original data and speed up the computation significantly. If you can provide further context I am happy to help you even vectorize the calculation instead of raw iterations.
Few points:
sum_
to 0 anyway why do you need user to provide it? just create a internal variable.a[i, 0:d[i[0]]][0]
is equivalent to a[i, 0]
since you always need 0th element for your computation. same goes for b[i, d[i[0]]][0]
np.ndindex(a.shape[:1])
use range
to simplify downstream indexing like i[0]
. You can directly use i
for indexing.