2

I know this adds consecutive columns of same index:

df['C'] = df['A'] + df['B']

But how to add columns of different index:

Lets say I have a dataframe like this:

df
   A   B    
0  9  40  
1  1  70  
2  5  80  
3  8  30  
4  7  50 

I need to create another column C which is the addition of current index row of column A(i.e. idx) and previous index row of column B(i.e. idx-1), such as:

df
   A   B   C  
0  9  40  (9)
1  1  70  (40 + 1)
2  5  80  (70 + 5)
3  8  30  (80 + 8)
4  7  50  (30 + 7)

final result should look like this:

df
   A   B  C  
0  9  40  9
1  1  70  41
2  5  80  75
3  8  30  88
4  7  50  37

3 Answers 3

4

You can use Series.shift.

df['C'] = df['A'] + df['B'].shift(1).fillna(0)
Sign up to request clarification or add additional context in comments.

Comments

1

Amother solution with Series.add:

df['C'] = df['A'].add(df['B'].shift(), fill_value=0)
print (df)
   A   B     C
0  9  40   9.0
1  1  70  41.0
2  5  80  75.0
3  8  30  88.0
4  7  50  37.0

Timings:

In [2]: %timeit df['C'] = df['A'].add(df['B'].shift(), fill_value=0)
1000 loops, best of 3: 457 µs per loop

In [3]: %timeit df['C1'] = df['A'] + df['B'].shift(1).fillna(0)
1000 loops, best of 3: 544 µs per loop

If need function, you can add column names (similar use for another solution):

def f(a,b,c):
    df[c] = df[a].add(df[b].shift(), fill_value=0)
    return df

print (f('A','B','C'))
  A   B     C
0  9  40   9.0
1  1  70  41.0
2  5  80  75.0
3  8  30  88.0
4  7  50  37.0

2 Comments

Elegant solutions. Thanks. Is there a way to put this in a function, such that there wont be a need to explicitly state the column names?
I am not sure if understand you correctly, but I try add solution.
0

Use shift:

df['C'] = df.A + df.B.shift().fillna(0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.