Sum of every two columns and leave one column in pandas dataframe

Viewed 419

My task is like this:

df=pd.DataFrame([(1,2,3,4,5,6),(1,2,3,4,5,6),(1,2,3,4,5,6)],columns=['a','b','c','d','e','f'])
Out:
    a b c d e f
0   1 2 3 4 5 6
1   1 2 3 4 5 6 
2   1 2 3 4 5 6

I want to do is the output dataframe looks like this:

Out
        s1 b s2  d  s3  f
    0   3  2  7  4  11  6
    1   3  2  7  4  11  6
    2   3  2  7  4  11  6

That is to say, sum the column (a,b),(c,d),(e,f) separately and keep each last column and rename the result columns names as (s1,s2,s3). Could anyone help solve this problem in Pandas? Thank you so much.

5 Answers

For one do

df['a'] = df['a'] + df['b']
df.rename(columns={col1: 's1')}, inplace=True)

You can use a loop to do all

  • the loop using enumerate and zip, generates

    (0,('a','b')), (1,('c','d')), (2,('e','f'))
    
  • use these indexes to do the sum and the renaming

import pandas as pd
cols = ['a','b','c','d','e','f']
df =pd.DataFrame([(1,2,3,4,5,6),(1,2,3,4,5,6),(1,2,3,4,5,6)],columns=cols)
    
for idx, (col1, col2) in enumerate(zip(cols[::2], cols[1::2])):
    df[col1] = df[col1] + df[col2]
    df.rename(columns={col1: 's'+str(idx+1)}, inplace=True)

print(df)

CODE DEMO

You can seelct columns by posistions by iloc, sum each 2 values and last rename columns by f-strings

i = 2
for x in range(0, len(df.columns), i):
    df.iloc[:, x] = df.iloc[:, x:x+i].sum(axis=1)
    df = df.rename(columns={df.columns[x]:f's{x // i + 1}'})
print (df)
   s1  b  s2  d  s3  f
0   3  2   7  4  11  6
1   3  2   7  4  11  6
2   3  2   7  4  11  6

You can try this:-

res = pd.DataFrame()
for i in range(len(df.columns)-1):
    if i%2==0:
        res[df.columns[i]] = df[df.columns[i]]+df[df.columns[i+1]]
    else:
        res[df.columns[i]] = df[df.columns[i]]

res['f'] = df[df.columns[-1]]
res.columns = ['s1', 'b', 's2', 'd', 's3', 'f']

Output:-

   s1  b  s2  d  s3  f
0   3  2   7  4  11  6
1   3  2   7  4  11  6
2   3  2   7  4  11  6
df=pd.DataFrame([(1,2,3,4,5,6),(1,2,3,4,5,6),(1,2,3,4,5,6)],columns=['a','b','c','d','e','f'])
df['s1'] = df['a'] + df['b']
df['s2'] = df['c'] + df['d']
df['s3'] = df['e'] + df['f']

df =  a  b  c  d  e  f  s1  s2  s3
   0  1  2  3  4  5  6   3   7  11
   1  1  2  3  4  5  6   3   7  11
   2  1  2  3  4  5  6   3   7  11

and you can remove the columns 'a', 'b', 'c'

df.pop('a')
df.pop('c')
df.pop('d')
df =  b  e  f  s1  s2  s3
   0  2  5  6   3   7  11
   1  2  5  6   3   7  11
   2  2  5  6   3   7  11

Jump is in steps of two; so we can split the dataframe with np.split :

res = np.split(df.to_numpy(), df.shape[-1] // 2, 1)

Next, we compute the new data, where we sum pairs of columns and keep the last column in each pair :

new_frame = np.hstack([np.vstack((np.sum(entry,1), entry[:,-1])).T for entry in res])

Create new column, taking into cognizance the jump of 2 :

new_cols = [f"s{ind//2+1}" if ind%2==0 else val for ind,val in enumerate(df.columns)]

Create new dataframe :

pd.DataFrame(new_frame, columns=new_cols)

    s1  b   s2  d   s3  f
0   3   2   7   4   11  6
1   3   2   7   4   11  6
2   3   2   7   4   11  6
Related