[英]Python dataframe sum rows
If I have a dataframe with n
rows, is there a way to set the ith row to be sum of row[i]
and row[i-1]
and do this so that the assignment to earlier rows is reflected in the latter rows? 如果我有一个包含
n
行的数据帧,是否有办法将第i行设置为row[i]
和row[i-1]
总和,并执行此操作,以便将对较早行的分配反映在后行中? I would really like to avoid loops if possible. 如果可能,我真的很想避免循环。
Example DF: DF示例:
SPY AAPL GOOG
2011-01-10 0.44 -0.81 1.80
2011-01-11 0.00 0.00 0.00
2011-01-12 -1.11 -2.77 -0.86
2011-01-13 -0.91 -4.02 -0.68
Sample pseudo code of summing two rows: 将两行相加的样本伪代码:
DF[2011-01-11] = DF[2011-01-10] + DF[2011-01-11]
DF[2011-01-12] = DF[2011-01-11] + DF[2011-01-12]
and so on. 等等。
based on your question, you are looking for a cumulative sum of each columns. 根据您的问题,您正在寻找每列的累积总和。 you could use the
cumsum()
method 您可以使用
cumsum()
方法
DF.cumsum()
SPY AAPL GOOG
2011-01-10 0.4400 -0.8100 1.8000
2011-01-11 0.4400 -0.8100 1.8000
2011-01-12 -0.6700 -3.5800 0.9400
2011-01-13 -1.5800 -7.6000 0.2600
使用DF.shift()
DF + DF.shift()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.