Extensions
Pandas extensions for latent-calendar
and primary interface for the package.
Provides a cal
accessor to DataFrame
and Series
instances for easy transformation and plotting after import of latent_calendar
.
Functionality includes:
- aggregation of events to wide format
- convolutions of wide formats
- making transformations and predictions with models
- plotting of events, predictions, and comparisons as calendars
Each DataFrame
will be either at event level or an aggregated wide format.
Methods that end in row
or by_row
will be for wide format DataFrames and will plot each row as a calendar.
Examples:
Plotting an event level Series as a calendar
import pandas as pd
import latent_calendar
dates = pd.date_range("2023-01-01", "2023-01-14", freq="h")
ser = (
pd.Series(dates)
.sample(10, random_state=42)
)
ser.cal.plot()
Transform event level DataFrame to wide format and plot
from latent_calendar.datasets import load_online_transactions
df = load_online_transactions()
# (n_customer, n_timeslots)
df_wide = (
df
.cal.aggregate_events("Customer ID", timestamp_col="InvoiceDate")
)
(
df_wide
.sample(n=12, random_state=42)
.cal.plot_by_row(max_cols=4)
)
Train a model and plot predictions
from latent_calendar import LatentCalendar
model = LatentCalendar(n_components=5, random_state=42)
model.fit(df_wide.to_numpy())
(
df_wide
.head(2)
.cal.plot_profile_by_row(model=model)
)
DataFrameAccessor
DataFrame accessor for latent_calendar accessed through cal
attribute of DataFrames.
Source code in latent_calendar/extensions.py
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 |
|
aggregate_events(by, timestamp_col, minutes=60, as_multiindex=True)
Transform event level DataFrame to wide format with groups as index.
Wrapper around create_raw_to_vocab_transformer
to transform to wide format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by
|
str | list[str]
|
column(s) to use as index |
required |
timestamp_col
|
str
|
column to use as timestamp |
required |
minutes
|
int
|
The number of minutes to discretize by. |
60
|
as_multiindex
|
bool
|
whether to use MultiIndex columns |
True
|
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame in wide format |
Source code in latent_calendar/extensions.py
conditional_probabilities(*, level=0)
Calculate conditional probabilities for each row over the level.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
level
|
int | str
|
level of the columns MultiIndex. Default 0 or day_of_week |
0
|
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with conditional probabilities |
Source code in latent_calendar/extensions.py
divide_by_even_rate()
Divide each row by the number of columns.
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with row-wise operations applied |
divide_by_max()
Divide each row by the max value.
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with row-wise operations applied |
divide_by_sum()
Divide each row by the sum of the row.
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with row-wise operations applied |
normalize(kind)
Row-wise operations on DataFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kind
|
Literal['max', 'probs', 'even_rate']
|
The normalization to apply. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with row-wise operations applied |
Source code in latent_calendar/extensions.py
plot(start_col, *, end_col=None, duration=None, alpha=None, cmap=None, day_labeler=DayLabeler(), time_labeler=TimeLabeler(), grid_lines=GridLines(), monday_start=True, ax=None)
Plot DataFrame of timestamps as a calendar.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
start_col
|
str
|
column with start timestamp |
required |
end_col
|
str | None
|
column with end timestamp |
None
|
duration
|
int | None
|
length of event in minutes. Alternative to end_col |
None
|
alpha
|
float
|
alpha value for the color |
None
|
cmap
|
function that maps floats to string colors |
None
|
|
monday_start
|
bool
|
whether to start the week on Monday or Sunday |
True
|
ax
|
Axes | None
|
optional matplotlib axis to plot on |
None
|
Returns:
Type | Description |
---|---|
Axes
|
Modified matplotlib axis |
Source code in latent_calendar/extensions.py
plot_across_column(start_col, grid_col, *, end_col=None, duration=None, day_labeler=DayLabeler(), time_labeler=TimeLabeler(), grid_lines=GridLines(), max_cols=3, alpha=None)
Plot DataFrame of timestamps as a calendar as grid across column values.
NA values are excluded
Parameters:
Name | Type | Description | Default |
---|---|---|---|
start_col
|
str
|
column with start timestamp |
required |
grid_col
|
str
|
column of values to use as grid |
required |
end_col
|
str | None
|
column with end timestamp |
None
|
duration
|
int | None
|
length of event in minutes. Alternative to end_col |
None
|
max_cols
|
int
|
max number of columns per row |
3
|
alpha
|
float
|
alpha value for the color |
None
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in latent_calendar/extensions.py
plot_by_row(*, max_cols=3, title_func=None, cmaps=None, day_labeler=DayLabeler(), time_labeler=TimeLabeler(), grid_lines=GridLines(), monday_start=True)
Plot each row of the DataFrame as a calendar plot. Data must have been transformed to wide format first.
Wrapper around latent_calendar.plot.plot_calendar_by_row
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_cols
|
int
|
max number of columns per row of grid |
3
|
title_func
|
TITLE_FUNC | None
|
function to generate title for each row |
None
|
day_labeler
|
DayLabeler
|
function to generate day labels |
DayLabeler()
|
time_labeler
|
TimeLabeler
|
function to generate time labels |
TimeLabeler()
|
cmaps
|
CMAP | ColorMap | CMAP_GENERATOR | None
|
optional generator of colormaps |
None
|
grid_lines
|
GridLines
|
optional grid lines |
GridLines()
|
monday_start
|
bool
|
whether to start the week on Monday or Sunday |
True
|
Returns:
Type | Description |
---|---|
None
|
None |
Source code in latent_calendar/extensions.py
plot_model_predictions_by_row(df_holdout, *, model, index_func=lambda idx: idx, divergent=True, day_labeler=DayLabeler(), time_labeler=TimeLabeler())
Plot model predictions for each row of the DataFrame. Data must have been transformed to wide format first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df_holdout
|
DataFrame
|
holdout DataFrame for comparison |
required |
model
|
LatentCalendar
|
model to use for prediction |
required |
index_func
|
function to generate title for each row |
lambda idx: idx
|
|
divergent
|
bool
|
whether to use divergent colormap |
True
|
day_labeler
|
DayLabeler
|
DayLabeler instance to use for day labels |
DayLabeler()
|
time_labeler
|
TimeLabeler
|
TimeLabeler instance to use for time labels |
TimeLabeler()
|
Returns:
Type | Description |
---|---|
ndarray
|
grid of axes |
Source code in latent_calendar/extensions.py
plot_profile_by_row(*, model, index_func=lambda idx: idx, include_components=True, day_labeler=DayLabeler(), time_labeler=TimeLabeler())
Plot each row of the DataFrame as a profile plot. Data must have been transformed to wide format first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
LatentCalendar
|
model to use for prediction and transform |
required |
index_func
|
function to generate title for each row |
lambda idx: idx
|
|
include_components
|
bool
|
whether to include components in the plot |
True
|
day_labeler
|
DayLabeler
|
DayLabeler instance to use for day labels |
DayLabeler()
|
time_labeler
|
TimeLabeler
|
TimeLabeler instance to use for time labels |
TimeLabeler()
|
Returns:
Type | Description |
---|---|
ndarray
|
grid of axes |
Source code in latent_calendar/extensions.py
plot_raw_and_predicted_by_row(*, model, index_func=lambda idx: idx, day_labeler=DayLabeler(), time_labeler=TimeLabeler())
Plot raw and predicted values for a model. Data must have been transformed to wide format first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
LatentCalendar
|
model to use for prediction |
required |
index_func
|
function to generate title for each row |
lambda idx: idx
|
|
day_labeler
|
DayLabeler
|
DayLabeler instance to use for day labels |
DayLabeler()
|
time_labeler
|
TimeLabeler
|
TimeLabeler instance to use for time labels |
TimeLabeler()
|
Returns:
Type | Description |
---|---|
ndarray
|
grid of axes |
Source code in latent_calendar/extensions.py
predict(*, model)
Predict DataFrame with model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
LatentCalendar
|
model to use for prediction |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with predicted values (wide format) |
Source code in latent_calendar/extensions.py
sum_next_hours(hours)
Sum the wide format over next hours.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hours
|
int
|
number of hours to sum over |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with summed values |
Source code in latent_calendar/extensions.py
sum_over_segments(df_segments)
Sum the wide format over user defined segments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df_segments
|
DataFrame
|
DataFrame in wide format with segments as index |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with columns as the segments and summed values |
Source code in latent_calendar/extensions.py
sum_over_vocab(aggregation='dow')
Sum the wide format to day of week or hour of day.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
aggregation
|
str
|
one of ['dow', 'hour'] |
'dow'
|
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with summed values |
Examples:
Sum to day of week
Source code in latent_calendar/extensions.py
timestamp_features(column, discretize=True, minutes=60, create_vocab=True)
Create day of week and proportion into day columns for event level DataFrame
Exposed as a method on DataFrame for convenience. Use cal.aggregate_events
instead to create the wide format DataFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column
|
str
|
The name of the timestamp column. |
required |
discretize
|
bool
|
Whether to discretize the hour column. |
True
|
minutes
|
int
|
The number of minutes to discretize by. Ingored if |
60
|
create_vocab
|
bool
|
Whether to create the vocab column. |
True
|
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with features added |
Source code in latent_calendar/extensions.py
transform(*, model)
Transform DataFrame with model.
Applies the dimensionality reduction to each row of the DataFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
LatentCalendar
|
model to use for transformation |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with transformed values |
Source code in latent_calendar/extensions.py
widen(column, as_int=True, minutes=60, multiindex=True)
Transform an aggregated DataFrame to wide calendar format.
Wrapper around LongToWide
transformer to transform to wide format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column
|
str
|
column to widen |
required |
as_int
|
bool
|
whether to cast the column to int |
True
|
minutes
|
int
|
number of minutes to |
60
|
multiindex
|
bool
|
whether to use a MultiIndex |
True
|
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame in wide format |
Source code in latent_calendar/extensions.py
SeriesAccessor
Series accessor for latent_calendar accessed through cal
attribute of Series.
Source code in latent_calendar/extensions.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
aggregate_events(minutes=60, as_multiindex=True)
Transform event level Series to row of wide format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
minutes
|
int
|
The number of minutes to discretize by. |
60
|
as_multiindex
|
bool
|
whether to use MultiIndex columns |
True
|
Returns:
Type | Description |
---|---|
Series
|
Series that would be row of wide format |
Examples:
Discretize datetime Series to 30 minutes
import pandas as pd
import matplotlib.pyplot as plt
from latent_calendar.datasets import load_chicago_bikes
df_trips = load_chicago_bikes()
start_times = df_trips["started_at"]
agg_start_times = start_times.cal.aggregate_events(minutes=30)
agg_start_times.cal.plot_row()
plt.show()
Source code in latent_calendar/extensions.py
conditional_probabilities(*, level=0)
Calculate conditional probabilities for each the row over the level.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
level
|
int | str
|
level of the column MultiIndex. Default 0 or day_of_week |
0
|
Returns:
Type | Description |
---|---|
Series
|
Series with conditional probabilities |
Source code in latent_calendar/extensions.py
plot(*, duration=5, alpha=None, cmap=None, day_labeler=DayLabeler(), time_labeler=TimeLabeler(), grid_lines=GridLines(), monday_start=True, ax=None)
Plot Series of timestamps as a calendar.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
duration
|
int
|
duration of each event in minutes |
5
|
alpha
|
float
|
alpha value for the color |
None
|
cmap
|
function that maps floats to string colors |
None
|
|
day_labeler
|
DayLabeler
|
DayLabeler instance |
DayLabeler()
|
time_labeler
|
TimeLabeler
|
TimeLabeler instance |
TimeLabeler()
|
grid_lines
|
GridLines
|
GridLines instance |
GridLines()
|
monday_start
|
bool
|
whether to start the week on Monday or Sunday |
True
|
ax
|
Axes | None
|
matplotlib axis to plot on |
None
|
Returns:
Type | Description |
---|---|
Axes
|
Modified matplotlib axis |
Source code in latent_calendar/extensions.py
plot_row(*, alpha=None, cmap=None, day_labeler=DayLabeler(), time_labeler=TimeLabeler(), grid_lines=GridLines(), monday_start=True, ax=None)
Plot Series of timestamps as a calendar.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
alpha
|
float
|
alpha value for the color |
None
|
cmap
|
function that maps floats to string colors |
None
|
|
monday_start
|
bool
|
whether to start the week on Monday or Sunday |
True
|
ax
|
Axes | None
|
matplotlib axis to plot on |
None
|
Returns:
Type | Description |
---|---|
Axes
|
Modified matplotlib axis |
Source code in latent_calendar/extensions.py
timestamp_features(discretize=True, minutes=60, create_vocab=True)
Create day of week and proportion into day columns.
Exposed as a method on Series for convenience.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
discretize
|
bool
|
Whether to discretize the hour column. |
True
|
minutes
|
int
|
The number of minutes to discretize by. Ingored if |
60
|
create_vocab
|
bool
|
Whether to create the vocab column. |
True
|
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with features |
Examples:
Create the features for some dates
timestamp day_of_week hour
0 2023-01-01 00:00:00 6 0.0
1 2023-01-01 01:00:00 6 1.0
2 2023-01-01 02:00:00 6 2.0
3 2023-01-01 03:00:00 6 3.0
4 2023-01-01 04:00:00 6 4.0
.. ... ... ...
308 2023-01-13 20:00:00 4 20.0
309 2023-01-13 21:00:00 4 21.0
310 2023-01-13 22:00:00 4 22.0
311 2023-01-13 23:00:00 4 23.0
312 2023-01-14 00:00:00 5 0.0
[313 rows x 3 columns]