Skip to content

Commit 4484843

Browse files
committed
Improve way of inserting columns
1 parent 1efe5f0 commit 4484843

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

download_analytics/metrics.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,21 @@ def _historical_groupby(downloads, groupbys=None):
3535
if groupbys is None:
3636
groupbys = downloads.set_index('timestamp').columns
3737

38+
new_columns = [] # Collect grouped DataFrames here
39+
3840
for groupby in groupbys:
3941
grouped = downloads.groupby([year_month, groupby])
4042
grouped_sizes = grouped.size().unstack(-1) # noqa: PD010
4143
if len(groupbys) > 1:
4244
grouped_sizes.columns = f"{groupby}='" + grouped_sizes.columns + "'"
45+
new_columns.append(grouped_sizes.fillna(0)) # Store for later
4346

44-
base[grouped_sizes.columns] = grouped_sizes.fillna(0)
47+
if new_columns:
48+
base = pd.concat([base] + new_columns, axis=1) # Add all columns at once
4549

4650
totals = base.sum()
4751
totals.name = 'total'
48-
base = pd.concat([base, totals], ignore_index=True)
52+
base = pd.concat([base, totals.to_frame().T], ignore_index=True)
4953

5054
return base.reset_index().iloc[::-1]
5155

0 commit comments

Comments
 (0)