| 1 |
import time |
| 2 |
import numpy as np |
| 3 |
import pandas as pd |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 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 |
|
| 20 |
gpby = df.groupby("indicator") |
| 21 |
means = gpby.mean() |
| 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 |
|
| 30 |
df_sub = df.query("indicator==@indicator")[rnd_cols] |
| 31 |
means_for_ind = df_sub.mean() |
| 32 |
total = means_for_ind.sum() |
| 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 |
|
| 45 |
df2 = pd.DataFrame({"indicator": np.random.randint(0, 10, SIZE)}) |
| 46 |
|
| 47 |
df = pd.concat( |
| 48 |
(df2, df), axis=1 |
| 49 |
) |
| 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() |