1

I want to extract a range of indices contained in the 'ranges' list from the 'nums' array.

For example:

ranges=np.arange(10, 100, 10).tolist() 
#[10, 20, 30, 40, 50, 60, 70, 80, 90]

nums=np.arange(10, 1000, 5.5)

Here, I want to extract indices 10 to 20, and then 20 to 30 and so on until indices 80 to 90 specified in the 'ranges' list from the 'nums' array. I'm not sure how to cycle between every two numbers through the 'ranges' list.

If I just had to extract 2-3 ranges of indices, I would just hard code the indices and slice-

idx1 = nums[10:21]
idx2 = nums[20:31]
idx3 = nums[30:41]

But this gets tedious to do for various combinations of ranges, especially in my original dataset with almost 100 ranges of indices to extract.

Appreciate any help on this.

2
  • Sounds like you just need a loop Commented Jul 9, 2020 at 16:01
  • Looks like it is just reshaping what you aim to do: nums[10:].reshape(-1,10). Commented Jul 9, 2020 at 16:02

3 Answers 3

2

Something like this?

>>> ranges = [10, 20, 35, 42]
>>> for start, end in zip(ranges[:-1], ranges[1:]):
...     print(start, end)
...
10 20
20 35
35 42

(Of course, do your extraction in place of print)

Sign up to request clarification or add additional context in comments.

Comments

2

You can use a for loop with a chosen step:

idxs = []

for n in range(10, 1000, 10):
    idx.append(nums[n:n+11])

Comments

1

This should do it :

dic={}
for i in np.transpose([ranges[:-1],ranges[1:]]):
     dic[str(i[0])+"-"+str(i[1])]=nums[i[0]:i[1]]
print(dic)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.