In python, is there a way to vectorize adding the previous row to the current one?
Question:
Is there a way for me to vectorize adding the values from one row to all the subsequent rows in a vectorized manner in python?
I was trying to use dataframe to get there but was struggling to vectorize it. This can be done with a for loop.
For example, if I use a table like this:
Table A
Index
A
B
C
1
10
11
12
2
0
0
0
3
0
1
2
4
7
0
1
and add this to another table:
Table B
Index
A
B
C
1
0
0
10
2
0
0
0
3
0
0
0
4
0
0
0
the result would be:
Index
A
B
C
1
10
11
22
2
10
11
22
3
10
12
24
4
17
12
25
The for loop of this would be something like this:
tableA.ix[0, :] = tableA.ix[0, :] + tableB.ix[i, :]
for i in range(1, len(tableA.index)):
tableA.ix[i, :] = tableA.ix[i-1, :] + tableB.ix[i, :]
Answers:
Try this;
df3 = df1.cumsum(axis = 0).add(df2.cumsum(axis = 0), fill_value=0)
df3["INDEX"] = range(1,df3.shape[0]+1)
# Output;
INDEX A B C
0 1 10 11 22
1 2 10 11 22
2 3 10 12 24
3 4 17 12 25
Is there a way for me to vectorize adding the values from one row to all the subsequent rows in a vectorized manner in python?
I was trying to use dataframe to get there but was struggling to vectorize it. This can be done with a for loop.
For example, if I use a table like this:
Table A
Index | A | B | C |
---|---|---|---|
1 | 10 | 11 | 12 |
2 | 0 | 0 | 0 |
3 | 0 | 1 | 2 |
4 | 7 | 0 | 1 |
and add this to another table:
Table B
Index | A | B | C |
---|---|---|---|
1 | 0 | 0 | 10 |
2 | 0 | 0 | 0 |
3 | 0 | 0 | 0 |
4 | 0 | 0 | 0 |
the result would be:
Index | A | B | C |
---|---|---|---|
1 | 10 | 11 | 22 |
2 | 10 | 11 | 22 |
3 | 10 | 12 | 24 |
4 | 17 | 12 | 25 |
The for loop of this would be something like this:
tableA.ix[0, :] = tableA.ix[0, :] + tableB.ix[i, :]
for i in range(1, len(tableA.index)):
tableA.ix[i, :] = tableA.ix[i-1, :] + tableB.ix[i, :]
Try this;
df3 = df1.cumsum(axis = 0).add(df2.cumsum(axis = 0), fill_value=0)
df3["INDEX"] = range(1,df3.shape[0]+1)
# Output;
INDEX A B C
0 1 10 11 22
1 2 10 11 22
2 3 10 12 24
3 4 17 12 25