简体   繁体   中英

Summing array values over a specific range with numpy

So I am trying to get the sum over a specific range of values in a text file using:

np.sum(d[a:b])

I am using a text file with 10000 entries. I know that we always start at zero. So my range is quite large ie; index 200-555 (including 200 and 555). I tried just for testing summing over a small range:

In [17]: np.sum(d[1:4])
Out[17]: 50.164228

But the above code summed from the 2nd block (labeled number 1 by python) until the third. The numbers are; (0-> 13.024) , 1-> 17.4529, 2-> 16.9382, 3-> 15.7731,( 4-> 11.7589), 5-> 14.5178.

zero is just for reference and it ignored the 4th-> 11.7589. Why?

When using range indexing in Python, the second index (the 4 in your case) is not an inclusive index. By specifying [1:4] , you're summing the elements from index 1 up to but not including index 4. Specify 5 as the second index if you want to include the element at index 4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM