Debian Codegraph @

test/issues/test-issue167.py

raw symbols SCIP
1 import time
2 import numpy as np
3 import pandas as pd
4
5 # this assumes you have memory_profiler installed
6 # if you want to use "@profile" on a function
7 # if not, we can ignore it with a pass-through decorator
8 if "profile" not in dir():
9
10 def profile(fn):
11 return fn
12
13
14 SIZE = 10_000_000
15
16
17 @profile
18 def get_mean_for_indicator_poor(df, indicator):
19 # poor way to use a groupby here, causes big allocation
20 gpby = df.groupby("indicator")
21 means = gpby.mean() # means by column
22 means_for_ind = means.loc[indicator]
23 total = means_for_ind.sum()
24 return total
25
26
27 @profile
28 def get_mean_for_indicator_better(df, indicator, rnd_cols):
29 # more memory efficient and faster way to solve this challenge
30 df_sub = df.query("indicator==@indicator")[rnd_cols]
31 means_for_ind = df_sub.mean() # means by column
32 total = means_for_ind.sum() # sum of rows
33 return total
34
35
36 @profile
37 def run():
38 arr = np.random.random((SIZE, 10))
39 print(f"{arr.shape} shape for our array")
40 df = pd.DataFrame(arr)
41 rnd_cols = [f"c_{n}" for n in df.columns]
42 df.columns = rnd_cols
43
44 # make a big dataframe with an indicator column and lots of random data
45 df2 = pd.DataFrame({"indicator": np.random.randint(0, 10, SIZE)})
46 # deliberately overwrite the first df
47 df = pd.concat(
48 (df2, df), axis=1
49 ) # PART OF DEMO - unexpected copy=True forces an expensive copy
50 print("Head of our df:")
51 print(df.head())
52
53 print("Print results to check that we get the result")
54 indicator = 2
55 print(
56 f"Mean for indicator {indicator} on better implementation {get_mean_for_indicator_better(df, indicator, rnd_cols):0.5f}"
57 )
58 print(
59 f"Mean for indicator {indicator} on poor implementation: {get_mean_for_indicator_poor(df, indicator):0.5f}"
60 )
61
62
63 if __name__ == "__main__":
64 run()