2

I have an array like this: A = ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) and would like to extract every 5th "and" 6th element from this row vector, leading to B = ([4,5,9,10,14,15]).

I know how to extract every 5th element: B = A[::5] but not how to extract two values after one another.

Jenni
  • 23
  • 3

4 Answers4

0

You can use:

A[4::5]

to get array([ 4, 9, 14]) and then concatenate and sort with A[::5].

rpoleski
  • 988
  • 5
  • 12
0

One way using numpy:

import numpy as np
A = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])

ids = np.ravel(np.array([np.array([4,5]) + i * np.array([5,5]) for i in range(3)] ))

A[ids]
array([ 4,  5,  9, 10, 14, 15])
FBruzzesi
  • 6,385
  • 3
  • 15
  • 37
0

You wrote every 5th and 6th element, so I undestrand it the following way:

  • divide the source Series into "parts", 6 elements each,
  • from each "part" take 2 last elements (5-th and 6-th).

So the expected result is (slightly other than you wrote):

  • 4 and 5 - 2 last elements from part 0 thru 5,
  • 10 and 11 - 2 last elements from part 6 thru 11,
  • 16 - from the third part (12 thru 17) take only 16, because the source Series does not contain 17.

To get just these elements, you can run:

pd.concat([s[4::6], s[5::6]]).sort_index().tolist()

Details:

  • s[4::6] - every 6-th element starting from 5-th (note that indexation starts from 0),
  • s[5::6] - every 6-th element starting from 6-th.
  • concat(...) - concatenate these 2 results,
  • sort_index() - restore the original order (assuming that the source Series has an ordered index),
  • tolist() - convert the above result (a Series) to plain list.

For your data sample the result is:

[4, 5, 10, 11, 16]

Other possible solution, this time based on splitting the source Series into parts of size 6 and taking element No 5 and 6 (if any) from each part:

np.concatenate([ tt[4:] for tt in np.array_split(s.values, np.ceil(s.size / 6)) ]).tolist()
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
0

You can build a mask and use the mask to extract the elements:

mask = (np.arange(len(A))%6 == np.array([[4],[5]])).any(0)
A[mask]
# array([ 4,  5, 10, 11, 16])
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74