Need to insert blank rows based on value of another row in pandas

Question:

I have a dataset in which I need to insert a blank below based on the value in the count column. For example, if the count columns have 2, then it should insert 2 rows below.

Data set

Account No  Date       Count 
7872416357  30-04-2022  2
2243931372  31-05-2022  0
5871537325  31-05-2022  2
1817653792  31-05-2022  0
9832713434  31-05-2022  2
4853617457  31-05-2022  2
4427388242  30-06-2022  1
4427388242  31-07-2022  0
4637657745  30-04-2022  1

Desired Output

Account No  Date       Count 
7872416357  30-04-2022  2
        
        
2243931372  31-05-2022  0
5871537325  31-05-2022  2
        
        
1817653792  31-05-2022  0
9832713434  31-05-2022  2
        
        
4853617457  31-05-2022  2
        
        
4427388242  30-06-2022  1
        
4427388242  31-07-2022  0

[Dataset]

[Desired Output]

Asked By: ankit vijay

||

Answers:

Something like the below should do:

import numpy as np
import pandas as pd

# Demonstration data
data = 'Number Count 12345 1 54321 3 12346 2'
data = np.array(data.split()).reshape((4,2))
df = pd.DataFrame(data[1:],columns=data[0])

# Add blank rows
df_new = pd.DataFrame()
for i, row in df.iterrows():
    df_new = df_new.append(row)
    for _ in range(int(row['Count'])):
        df_new = df_new.append(pd.Series(), ignore_index=True)

print(df_new)

Output:

  Number Count
0  12345     1
1    NaN   NaN
2  54321     3
3    NaN   NaN
4    NaN   NaN
5    NaN   NaN
6  12346     2
7    NaN   NaN
8    NaN   NaN
Answered By: Duc Nguyen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.