Fxs7576
Fxs7576

Reputation: 1341

Creating a Cumulative Frequency Column in a Dataframe Python

I am trying to create a new column named 'Cumulative Frequency' in a data frame where it consists of all the previous frequencies to the frequency for the current row as shown here.

enter image description here

What is the way to do this?

Upvotes: 5

Views: 18716

Answers (1)

EdChum
EdChum

Reputation: 394459

You want cumsum:

df['Cumulative Frequency'] = df['Frequency'].cumsum()

Example:

In [23]:
df = pd.DataFrame({'Frequency':np.arange(10)})
df

Out[23]:
   Frequency
0          0
1          1
2          2
3          3
4          4
5          5
6          6
7          7
8          8
9          9

In [24]:
df['Cumulative Frequency'] = df['Frequency'].cumsum()
df

Out[24]:
   Frequency  Cumulative Frequency
0          0                     0
1          1                     1
2          2                     3
3          3                     6
4          4                    10
5          5                    15
6          6                    21
7          7                    28
8          8                    36
9          9                    45

Upvotes: 11

Related Questions