2

I have a df which sums every 5 rows in 'Costs' and puts into 'Sum'. Now I would like to add 4 empty rows between each value in 'Sum' to have it at the start of each 5 rows. What would be the most efficient and straight forward way to achieve this?

Input:

  Costs |  Sum  
 -------|------- 
   1000 | 10000 
   1500 | 22500 
   2000 | 35000 
   2500 |       
   3000 |       
   3500 |       
   4000 |       
   4500 |       
   5000 |       
   5500 |       
   6000 |       
   6500 |       
   7000 |       
   7500 |       
   8000 |       

Output:

  Costs |  Sum  
 -------|------- 
   1000 | 10000 
   1500 |       
   2000 |       
   2500 |       
   3000 |       
   3500 | 22500 
   4000 |       
   4500 |       
   5000 |       
   5500 |       
   6000 | 35000 

2 Answers 2

2

IIUC ,you can repeat the Sum column and check for the first of the duplicated value , then assign:

n=5
u = df['Sum'].replace('',np.nan).dropna().repeat(n)
df['New_sum'] = np.where(~u.index.duplicated(),u,'')

print(df)

    Costs    Sum New_sum
0    1000  10000   10000
1    1500  22500        
2    2000  35000        
3    2500               
4    3000               
5    3500          22500
6    4000               
7    4500               
8    5000               
9    5500               
10   6000          35000
11   6500               
12   7000               
13   7500               
14   8000               
Sign up to request clarification or add additional context in comments.

Comments

2

Let's try groupby + transform then mask the duplicated values:

g = df.index // 5
df['Sum'] = df['Costs'].groupby(g).transform('sum').mask(g.duplicated(), '')

Result:

    Costs    Sum
0    1000  10000
1    1500       
2    2000       
3    2500       
4    3000       
5    3500  22500
6    4000       
7    4500       
8    5000       
9    5500       
10   6000  35000
11   6500       
12   7000       
13   7500       
14   8000       

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.