File tree Expand file tree Collapse file tree 3 files changed +20
-25
lines changed
Expand file tree Collapse file tree 3 files changed +20
-25
lines changed Original file line number Diff line number Diff line change 55def loop_cumsum (products ):
66 cumulative_sum = []
77 for product in products .itertuples ():
8+ income = product .sales * product .unit_price
89 if cumulative_sum :
9- cumulative_sum .append (
10- cumulative_sum [- 1 ] + (product .sales * product .unit_price )
11- )
10+ cumulative_sum .append (cumulative_sum [- 1 ] + income )
1211 else :
13- cumulative_sum .append (product . sales * product . unit_price )
12+ cumulative_sum .append (income )
1413 return products .assign (cumulative_income = cumulative_sum )
1514
1615
Original file line number Diff line number Diff line change 55def loop_cumsum (products ):
66 cumulative_sum = []
77 for product in products .itertuples ():
8+ income = product .sales * product .unit_price
89 if cumulative_sum :
9- cumulative_sum .append (
10- cumulative_sum [- 1 ] + (product .sales * product .unit_price )
11- )
10+ cumulative_sum .append (cumulative_sum [- 1 ] + income )
1211 else :
13- cumulative_sum .append (product . sales * product . unit_price )
12+ cumulative_sum .append (income )
1413 return products .assign (cumulative_income = cumulative_sum )
1514
1615
Original file line number Diff line number Diff line change 11# %%
2-
32import pandas as pd
43
4+ # %% Get the cumulative sum with .itertuples()
5+ products = pd .read_csv ("resources/products.csv" )
6+
7+ cumulative_sum = []
8+
9+ for product in products .itertuples ():
10+ income = product .sales * product .unit_price
11+ if cumulative_sum :
12+ cumulative_sum .append (cumulative_sum [- 1 ] + income )
13+ else :
14+ cumulative_sum .append (income )
15+
16+ products .assign (cumulative_income = cumulative_sum )
17+
518# %% To get cumulative sum, instead of looping, you can create intermediate
619# columns and use .cumsum()
720products = (
1225 )
1326 .drop (columns = "income" )
1427)
15-
16- # %% The equivalent way to do that with only .itertuples()
17- products = pd .read_csv ("resources/products.csv" )
18-
19- cumulative_sum = []
20-
21- for product in products .itertuples ():
22- if cumulative_sum :
23- cumulative_sum .append (
24- cumulative_sum [- 1 ] + (product .sales * product .unit_price )
25- )
26- else :
27- cumulative_sum .append (product .sales * product .unit_price )
28-
29- products .assign (cumulative_income = cumulative_sum )
30- # %%
You can’t perform that action at this time.
0 commit comments