Open In App

How to Copy a Pandas DataFrame Row to Multiple Other Rows?

Last Updated : 02 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To copy a row from a Pandas DataFrame to multiple other rows, combination of copy() and loc[] methods are used more oftem. The copy() method creates a new copy of the row. Let's discuss all the methods with quick examples:

Method 1: Using loc and copy

This method involves selecting a specific row using the loc method and then copying it to other rows within the same or another DataFrame.

  1. Choose the row you want to copy.
  2. Allocate the copied row to multiple rows.
Python
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]})

# Copy the second row (index 1) to multiple other rows
df.loc[3] = df.loc[1].copy()
df.loc[4] = df.loc[1].copy()

print(df)

Output
   A  B
0  1  4
1  2  5
2  3  6
3  2  5
4  2  5

Method 2: Using concat for Multiple Rows

If you need to copy and append multiple rows from one DataFrame to another, consider using the pandas concat function. This approach is useful when you need to duplicate a row multiple times and insert it into a DataFrame.

Python
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]})
new_rows = pd.DataFrame({'A': [9,10], 'B': [11,12]})

# Concatenate the new rows with the existing DataFrame
df = pd.concat([df, new_rows], ignore_index=True)
print(df)

Output
    A   B
0   1   4
1   2   5
2   3   6
3   9  11
4  10  12

Method 3: Using NumPy's repeat to Replicate Rows

NumPy's repeat function can be used to replicate the rows of a DataFrame multiple times. This method is efficient, especially for larger DataFrames, as it operates directly on the underlying NumPy array.

Python
import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Replicate each row in df three times
df_replicated = pd.DataFrame(np.repeat(df.values, repeats=3, axis=0), columns=df.columns)
print(df_replicated)

Output
   A  B
0  1  4
1  1  4
2  1  4
3  2  5
4  2  5
5  2  5
6  3  6
7  3  6
8  3  6

np.repeat(df.values, repeats=3, axis=0), replicates each row in df three times. The axis=0 ensures that rows are repeated, not columns.


Next Article
Practice Tags :

Similar Reads