Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 589
Mika Avatar asked Jan 24 '26 11:01

Mika


1 Answers

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
like image 195
jezrael Avatar answered Jan 27 '26 01:01

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!