Reputation: 4571
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
Upvotes: 2
Views: 786
Reputation: 863166
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
Upvotes: 1
Reputation: 19114
You can use Series.shift
.
df['C'] = df['A'] + df['B'].shift(1).fillna(0)
Upvotes: 4