How can I duplicate a row or column in a numpy array?

Having this array numpy

:

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

      

How to duplicate the line of example 1 to get this:

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

      

+3


source to share


2 answers


Approach # 1

One approach with np.insert

-

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

      

For duplicate columns use it along axis=1

-

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

      

Place as functions to have total number of duplicates -

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)

      



Example 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]])

      

Total mileage -

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]])

      

+6


source


Index oversampling?



>>> 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]])

      

+4


source







All Articles