Repeat or Replicate the column multiple times in pandas

In This Section we will be focusing on how to repeat the column multiple times in pandas python. There are multiple ways to do it, we will replicate the single column multiple times in pandas using concat() function and We also repeat or replicate a column name in the original dataframe  using concat() function. let’s look at each of these cases in pandas with an example for each.

  • Repeat or replicate the column multiple times in pandas python – Replicate the single column multiple times
  • Repeat or replicate the column multiple times in pandas python – Replicate the column with the original dataframe

 

Create Dataframe:

 

#Create a DataFrame

import pandas as pd
import numpy as np

d = { 'Name':['Alisa','Bobby','Cathrine','Jodha','Raghu','Ram'],
'Maths':[76,73,83,93,89,94],
'Science':[85,41,55,75,81,97],
'Geography':[78,65,55,88,87,98]}


df = pd.DataFrame(d,columns=['Name','Maths','Science','Geography'])
df

dataframe:

Repeat-or-Replicate-the-column-multiple-times-in-pandas-1

 

 

Repeat or replicate the Single column multiple times in pandas python

We will use simple concat function which will concat the single column multiple times which will in turn replicate the single column multiple times in pandas python. In the below example we have replicated the name column multiple times (4 times) and given the name for each column

 

##### repeat the column multiple times : using concat() function

n = 4
df_repeat=pd.concat([df['Name']] * (n), axis=1, ignore_index=True)
df_repeat.columns = ['A','B','C','D']

df_repeat

So the resultant dataframe with single column repeated multiple times in pandas is

Repeat-or-Replicate-the-column-multiple-times-in-pandas-2

 

 

 

Replicate the column multiple times in pandas python – Replicate the column with the original dataframe

First we will create the copy of dataframe and then We will use simple concat function to replicate the single column multiple times(4 times) and then we will concatenate both original dataframe and repeated dataframe. Which in turn will repeat the specific column multiple times  in pandas python along with the original dataframe.

 
##### repeat the column multiple times and concatenate with original dataframe

df_original=df.copy()
n = 4

df_repeat=pd.concat([df['Name']] * (n), axis=1, ignore_index=True)
df_repeat.columns = ['A','B','C','D']

df_original=pd.concat([df_original,df_repeat],axis=1)
df_original

In the above example we have replicated the name column multiple times (4 times) and given the name for each column and then concatenated the result with original dataframe . So the resultant dataframe will be

Repeat-or-Replicate-the-column-multiple-times-in-pandas-3

 

 

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts