- Given the following array, where the elements in the array are a value at index
[0]
, and its frequency at index[1]
.
JavaScript
x
14
14
1
import numpy as np
2
3
a = np.array([[767, 5], [770, 5], [772, 7], [779, 7], [781, 5], [782, 7], [787, 5]])
4
5
# values
6
v = a[:, 0]
7
8
array([767, 770, 772, 779, 781, 782, 787])
9
10
# frequencies
11
f = a[:, 1]
12
13
array([5, 5, 7, 7, 5, 7, 5])
14
- I need an array that is the length of the sum of the
frequencies
, filled withv
, based on their respective frequency.
JavaScript
1
2
1
[767, 767, 767, 767, 767, 770, 770, 770, 770, 770, 772, 772, 772, 772, 772, 772, 772, 779, 779, 779, 779, 779, 779, 779, 781, 781, 781, 781, 781, 782, 782, 782, 782, 782, 782, 782, 787, 787, 787, 787, 787]
2
- This can be done with
JavaScript
1
10
10
1
# a for-loop
2
ix = list()
3
4
for (x, y) in a:
5
l = [x] * y
6
ix.extend(l)
7
8
# a list-comprehension
9
ix = [v for (x, y) in a for v in [x]*y]
10
How can I do this with a vectorized
numpy
method?- No
for-loops
- No
pandas
- No
I thought of creating an array of zeros, whose length is the sum of frequencies, but I’m not certain how to fill it.
JavaScript
1
2
1
za = np.zeros(sum(f))
2
Advertisement
Answer
Use numpy.repeat
:
JavaScript
1
3
1
np.repeat(a[:, 0], a[:, 1])
2
# np.repeat(*a.T) # In case its (n, 2) shaped
3
Output:
JavaScript
1
5
1
array([767, 767, 767, 767, 767, 770, 770, 770, 770, 770, 772, 772, 772,
2
772, 772, 772, 772, 779, 779, 779, 779, 779, 779, 779, 781, 781,
3
781, 781, 781, 782, 782, 782, 782, 782, 782, 782, 787, 787, 787,
4
787, 787])
5