There is an array of numpy . How can you add together all the elements of the array or selective, for example, from 5 to 100 without using cycles?

  • с 5 по 100 - do you mean indexes or values? - MaxU
  • The indices of the elements of the array - Alexei Voronov

1 answer 1

Example:

 In [83]: import numpy as np In [84]: a = np.random.randint(0, 10, 15) In [85]: a Out[85]: array([7, 8, 8, 6, 4, 0, 3, 0, 4, 0, 8, 0, 1, 4, 5]) 

summarize items with indices from 5 to 10:

 In [86]: a[5:10] Out[86]: array([0, 3, 0, 4, 0]) In [87]: a[5:10].sum() Out[87]: 7 

summarize items with values ​​from 5 to 7:

 In [88]: a[(a >= 5) & (a <= 7)] Out[88]: array([7, 6, 5]) In [89]: a[(a >= 5) & (a <= 7)].sum() Out[89]: 18 

PS add up all the elements:

 In [105]: a.sum() Out[105]: 58