Skip to content

⚡️ Speed up function groupby_mean by 6,392% #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/numpy_pandas/dataframe_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,20 @@ def dataframe_filter(df: pd.DataFrame, column: str, value: Any) -> pd.DataFrame:


def groupby_mean(df: pd.DataFrame, group_col: str, value_col: str) -> dict[Any, float]:
# Extract columns as numpy arrays for fast access
groups = df[group_col].values
values = df[value_col].values
sums = {}
counts = {}
for i in range(len(df)):
group = df.iloc[i][group_col]
value = df.iloc[i][value_col]
for group, value in zip(groups, values):
if group in sums:
sums[group] += value
counts[group] += 1
else:
sums[group] = value
counts[group] = 1
result = {}
for group in sums:
result[group] = sums[group] / counts[group]
# Compute means
result = {group: sums[group] / counts[group] for group in sums}
return result


Expand Down Expand Up @@ -66,14 +66,17 @@ def pivot_table(

def agg_func(values):
return sum(values) / len(values)

elif aggfunc == "sum":

def agg_func(values):
return sum(values)

elif aggfunc == "count":

def agg_func(values):
return len(values)

else:
raise ValueError(f"Unsupported aggregation function: {aggfunc}")
grouped_data = {}
Expand Down