Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate a row or column in a numpy array?

Having this numpy array:

[[0 1 2]
 [3 4 5]
 [6 7 8]] 

How do I duplicate for example row 1 so I get the below?:

[[0 1 2]
 [3 4 5]
 [3 4 5]
 [6 7 8]] 
like image 359
EquipDev Avatar asked Dec 02 '22 13:12

EquipDev


2 Answers

Approach #1

One approach with np.insert -

np.insert(a,2,a[1],axis=0)

For duplicating columns, use it along axis=1 -

np.insert(a,2,a[:,1],axis=1)

Put as functions to have generic number of duplications -

def dup_rows(a, indx, num_dups=1):
    return np.insert(a,[indx+1]*num_dups,a[indx],axis=0)

def dup_cols(a, indx, num_dups=1):
    return np.insert(a,[indx+1]*num_dups,a[:,[indx]],axis=1)

Sample run -

In [82]: a
Out[82]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [83]: np.insert(a,2,a[1],axis=0)
Out[83]: 
array([[0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8]])

In [141]: np.insert(a,2,a[:,1],axis=1)
Out[141]: 
array([[0, 1, 1, 2],
       [3, 4, 4, 5],
       [6, 7, 7, 8]])

Generic case runs -

In [255]: a
Out[255]: 
array([[19, 65, 87, 46, 85],
       [18, 45, 90, 26, 31],
       [49, 35, 34, 62, 24],
       [47, 85, 63, 91, 33],
       [54, 37, 89, 79, 50],
       [53, 54, 66, 59, 38]])

In [256]: dup_rows(a, indx=4, num_dups=3)
Out[256]: 
array([[19, 65, 87, 46, 85],
       [18, 45, 90, 26, 31],
       [49, 35, 34, 62, 24],
       [47, 85, 63, 91, 33],
       [54, 37, 89, 79, 50],
       [54, 37, 89, 79, 50],
       [54, 37, 89, 79, 50],
       [54, 37, 89, 79, 50],
       [53, 54, 66, 59, 38]])

In [253]: dup_cols(a, indx=2, num_dups=2)
Out[253]: 
array([[19, 65, 87, 87, 87, 46, 85],
       [18, 45, 90, 90, 90, 26, 31],
       [49, 35, 34, 34, 34, 62, 24],
       [47, 85, 63, 63, 63, 91, 33],
       [54, 37, 89, 89, 89, 79, 50],
       [53, 54, 66, 66, 66, 59, 38]])

Approach #2

Another with np.repeat -

In [102]: reps = np.ones(a.shape[0],dtype=int)

In [103]: reps[1] = 2 # duplication factor

In [104]: np.repeat(a,reps,axis=0)
Out[104]: 
array([[0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8]])
like image 108
Divakar Avatar answered Dec 31 '22 13:12

Divakar


By oversampling the index?

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>>
>>> a[[0,1,1,2]]
array([[0, 1, 2],
       [3, 4, 5],
       [3, 4, 5],
       [6, 7, 8]])
like image 24
Moses Koledoye Avatar answered Dec 31 '22 13:12

Moses Koledoye