Issue
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
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.