0

Suppose I have the following feature matrix X (ie. with 4 rows and 3 features):

X = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])

(array([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]]),

How do I duplicate say, the 1st and 2nd row twice, the 3rd row 3 times and no duplication in the 4th row, ie. I want to get this:

(array([[ 1,  2,  3],
        [ 1,  2,  3]
        [ 4,  5,  6],
        [ 4,  5,  6]
        [ 7,  8,  9],
        [ 7,  8,  9]
        [ 7,  8,  9]
        [10, 11, 12]]),

Is there a way for me to multiply the features matrix X with an array of weights, say something like this:

np.array([2,2,3,1])

Thanks in advance.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Leockl
  • 1,906
  • 5
  • 18
  • 51

2 Answers2

0

You can do it through indexing:

repeats = np.array([2,2,3,1])
indices = np.repeat(range(len(X)), repeats)
X[indices]

Where indices is

array([0, 0, 1, 1, 2, 2, 2, 3])
BlackBear
  • 22,411
  • 10
  • 48
  • 86
0
np.repeat(X, [2, 2, 3, 1], axis=0)
Manoj Khatua
  • 123
  • 8