简体   繁体   English

Pandas Dataframe ......如何增量添加行的值?

[英]Pandas Dataframe … how to incrementally add values of rows?

Is there an easy way to sum the value of all the rows above the current row in an adjacent column?是否有一种简单的方法可以对相邻列中当前行上方的所有行的值求和? Click on the image below to see what I'm trying to make.单击下面的图片查看我正在尝试制作的内容。 It's easier to see it than explain it.看到它比解释它更容易。

Text explanation: I'm trying to create a chart where column B is either the sum or percent of total of all the rows in A that are above it.文字说明:我正在尝试创建一个图表,其中 B 列是 A 中位于其上方的所有行的总和或总数的百分比。 That way I can quickly visualize where the quartile, third, etc are in the dataframe.这样我就可以快速可视化数据框中的四分位数、第三位数等位置。 I'm familiar with the percentile function我熟悉百分位函数

but I'm not sure I can get it to do exactly what I want it to do.但我不确定我能否让它完全按照我的意愿去做。 Image below as well as text version:下图以及文字版:

Text Version文字版

1--1%
1--2%
4--6%
4--10%
2--12%

... and so on to 100 percent. ... 以此类推到 100%。

Do i need to write a for loop to do this?我需要写一个 for 循环来做到这一点吗?

Excel Chart: Excel图表:
在此处输入图片说明

you can use cumsum for this:您可以为此使用cumsum

import numpy as np
import pandas as pd
df = pd.DataFrame(data=dict(x=[13,22,34,21,33,41,87,24,41,22,18,12,13]))
df["percent"] = (100*df.x.cumsum()/df.x.sum()).round(1)

output:输出:

     x  percent
0   13      3.4
1   22      9.2
2   34     18.1
3   21     23.6
4   33     32.3
5   41     43.0
6   87     65.9
7   24     72.2
8   41     82.9
9   22     88.7
10  18     93.4
11  12     96.6
12  13    100.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM