简体   繁体   中英

Extract specific elements from array to create ranges

I want to extract very specific elements from an array to create various ranges.

For example,

ranges = np.arange(0, 525, 25)
#array([  0,  25,  50,  75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500])

I want to create ranges that output as this-

0 50
75 125
150 200
225 275
300 350
375 425
450 500

I know if I want to extract every number into a range, I can write something like this-

for start, end in zip(ranges[:-1], ranges[1:]):
    print(start, end)

Which would give the result-

0 50
25 75
50 100
75 125
100 150
125 175
150 200
175 225
200 250
225 275
250 300
275 325
300 350
325 375
350 400
375 425
400 450
425 475

However, I'm not sure how to extract every other element from the array.

There is no need to stack anything here, or create more buffers than the one you already have. A couple of reshapes and simple indices should do the trick.

Notice that you are taking the first and last element in a sequence of three. That means you can truncate your array to a multiple of three, reshape to have N rows of three elements, and simply extract the first and last one of each.

k = 3
ranges = np.arange(0, 525, 25)
ranges[:ranges.size - ranges.size % k].reshape(-1, k)[:, ::k - 1]

Here is a breakdown of the one-liner:

trimmed_to_multiple = ranges[:ranges.size - ranges.size % k]
reshaped_to_n_by_k = trimmed_to_multiple.reshape(-1, k)
first_and_last_column_only = reshaped_to_n_by_k[:, ::k - 1]

You can create your two ranges, then stack them on the column axis:

np.stack((np.arange(0, 500, 75), np.arange(50, 550, 75)), axis=1)

Generalized:

>>> start = 50
>>> step = 75
>>> end = 550
>>> np.stack((np.arange(0, end - start, step), np.arange(start, end, step)), axis=1)
array([[  0,  50],
       [ 75, 125],
       [150, 200],
       [225, 275],
       [300, 350],
       [375, 425],
       [450, 500]])
lowestMidPoint, highestMidPoint = 25, 475
ranges = [[midpoint-25, midpoint+25] for midpoint in range(lowestMidPoint,highestMidPoint+1,75)]

will get you the results as an array of arrays. You can then just call np.array(ranges) to get it in numpy.

To answer your question "how do i get every other entry in the array?"... if you have a numpy array

out = 
  1 2
  3 4
  5 6

you can slice out as follows

stride = 2
out[::stride,:]

to get every other row

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