Avij
Avij

Reputation: 694

Add values of a column to each other in pandas

I have a df with let's say 4 cols A,B,C,D(in real 50+ cols). I wish to add values of the cols to each other. For ex:- df['A'][0]=df['A'][0]+df['A'][1] and so on df['B'][0]... .

    col1 col2   col3
A   1    222    abc
B   2    433    dfg
C   3    111    tyu
D   4    222    iop

Should become like :-

    **col1** col2   col3
A    3     222     abc
B    5     433     dfg
C    7     111     tyu
D    4     222     iop

I have created a for loop to do so and after modification i am assigning back the result to the respective cols.

for k,g in colIndividual.iteritems():
    if(k+1<len(colIndividual)):
        print(g+colIndividual[colIndividual.index[k+1]])

However, being new to python world i don't know is it the correct and beautiful way to code this logic. This would impact the performance as in future this df might get increased to more than 50 columns. Could you please help me here? Thanks for your kind help.

Upvotes: 1

Views: 122

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

df['col1'].rolling(2).sum().shift(-1).fillna(df['col1'])

Output:

   col1  col2 col3
A   3.0   222  abc
B   5.0   433  dfg
C   7.0   111  tyu
D   4.0   222  iop

Upvotes: 2

Related Questions