Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

python 3.x - Dataframe: Computed row based on cell above and cell on the left

I have a dataframe with a bunch of integer values. I then compute the column totals and append it as a new row to the dataframe. So far so good.

Now I want to append another computed row where the value of each cell is the sum of cell above and the cell on the left. You can see what I mean below:

 ----------------------------------------------------------------
|250000 |0      |145000 |145000 |220000 |165000 |145000 |145000  |
 ----------------------------------------------------------------
|250000 |250000 |395000 |540000 |760000 |925000 |1070000|1215000 |
 ----------------------------------------------------------------

How can this be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you need Series.cumsum with select last row (total row) by DataFrame.iloc:

df = pd.DataFrame({
         'B':[4,5,4],
         'C':[7,8,9],
         'D':[1,3,5],
         'E':[5,3,6],
})

df.loc['sum'] = df.sum()
df.loc['cumsum'] = df.iloc[-1].cumsum()

#if need only cumsum row
#df.loc['cumsum'] = df.sum().cumsum()
print (df)
         B   C   D   E
0        4   7   1   5
1        5   8   3   3
2        4   9   5   6
sum     13  24   9  14
cumsum  13  37  46  60

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...