Repeat Rows in DataFrame N Times

Given a pandas dataframe, we have to repeat rows in dataframe n times.
Submitted by Pranit Sharma, on September 09, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Pandas Rows

Rows in pandas are generally marked with the index number but in pandas, we can also assign index names according to the needs. In pandas, we can create, read, update, and delete a column or row value. The index is the number of rows that ranges from 0 to n-1, so if the index is 0, it represents the first row and the n-1th index represents the last row.

Problem statement

Suppose, we have a DataFrame with two columns "letter" and "times", "times" is a numeric column and contains some integer values. We need to repeat the letter's value n number of times and n is its corresponding times value.

Repeating rows in dataframe n times

For this purpose, we will access the index of the DataFrame and for each index, we will use the repeat() method inside which we will pass the value of times column.

Let us understand with the help of an example,

Python program to repeat rows in dataframe n times

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'letter':['a','b','c','d'],
    'times':[2,3,1,4]
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n")

# Repeating each row
result = df.loc[df.index.repeat(df.times)]

# Display result
print("Result:\n",result)

Output

The output of the above program is:

Repeat Rows in DataFrame N Times

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.