Skip to content

PERF: Optimise to_long_format by eliminating intermediate DataFrame allocations - #1675

Merged
CamDavidsonPilon merged 1 commit into
CamDavidsonPilon:masterfrom
matheusft:perf-optimize-to-long-format
Mar 7, 2026
Merged

PERF: Optimise to_long_format by eliminating intermediate DataFrame allocations#1675
CamDavidsonPilon merged 1 commit into
CamDavidsonPilon:masterfrom
matheusft:perf-optimize-to-long-format

Conversation

@matheusft

Copy link
Copy Markdown
Contributor

Description

This PR improves the performance of lifelines.utils.to_long_format.

The previous implementation relied on method chaining (df.assign(...).drop(...)), which inadvertently triggered two full DataFrame allocations in memory:

  1. assign created the first copy to append the new columns.
  2. drop created a second copy to remove the duration_col.

By refactoring this to perform a single explicit .copy() followed by fast, in-place operations (.pop() and direct assignment), we effectively halve the memory overhead and noticeably speed up execution on large DataFrames.

This change introduces no breaking changes and is fully backward-compatible.

Type of change

  • Performance improvement (non-breaking change that speeds up existing functionality)
  • Bug fix
  • New feature

Replaced chained `assign` and `drop` methods with a single `.copy()`
and an in-place `.pop()`. This prevents pandas from allocating memory
for intermediate DataFrames, resulting in faster execution and reduced
memory usage on large survival datasets.
@CamDavidsonPilon

CamDavidsonPilon commented Mar 6, 2026

Copy link
Copy Markdown
Owner

👍 I love perf wins like this! Have any numbers to share?

@matheusft

Copy link
Copy Markdown
Contributor Author

Here are the performance numbers comparing the existing new_to_long_format with the optimised original_to_long_format, using a df (203,769 rows × 43 columns, no missing data, ~29.5 MB):

⏱️ Performance

Function Median time (sec) Mean (sec) Speed vs. slow
new_to_long_format 0.0063 0.00635 ~1.8× faster
original_to_long_format 0.0112 0.01108 baseline

Numbers obtained after running each function 10x

@CamDavidsonPilon
CamDavidsonPilon merged commit 7a8fc34 into CamDavidsonPilon:master Mar 7, 2026
7 of 11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants