Please can you help me solve this problem:
I am trying to add two rows in my dataframe and save the result in a new column but it has not worked with the code with which I am trying to solve it.
These are the data:
The idea would be to add the first two data (rows 0 and 1) of the column Balance_total and save them in a new column with the results, then add the two data that follow (rows 2 and 3) and save the result in the new column and so on, adding two by two.
So far I have been trying with various codes not getting the result:
dftotals['variation']=dftotals.iloc[:,[0,1]].sum(axis = 0)
Beforehand thank you very much
I think a relatively simple method would be to use a " rolling window " of size 2 and apply
.sum()
to the result of that window.To illustrate, I'm going to use data with smaller numeric values, because otherwise you don't see anything (besides such large numbers being converted to float by pandas, so you see even less). Let's start with the following input dataframe:
My idea is to apply
df.Saldo_total.rolling(2).sum()
. This goes through the columnSaldo_total
grouping each data with the previous one and adding them. So in row 0 the result will be NaN because there is no previous data. In row 1 the result will be 6 (current value = 3 plus previous value = 3). In row 2 the value will be 2+3=5, in row 3 it will be 6+2=8, etc. The results are therefore:This is pretty much what you were looking for except you would have to "scroll up" the results to remove the Nan from row 0 and change it to 6.0 etc. That is achieved with
.shift(-1)
. So:In any of the two ways, the results you are looking for are in the even indices (0, 2, 4...) those of the odd indices in principle do not interest you. It's not clear from your question how to fill in the value of the odd indices. You may want to repeat the same value that appears in the even indices, you may want to pad them with NaN.
Filling them with NaN is easy. It is enough to assign
np.nan
to the indices whose module 2 comes out different from zero. By the way, we save the result in a new column of the dataframe as you requested:The new dataframe looks like this:
Finally, if you don't want those
NaN
you.fillna()
can use.fillna(method="ffill")
: