Column-Generating Pipeline Stagese
Column generation pdpipe PdPipelineStages.
Attributes
Classes
Bin
Bases: PdPipelineStage
A pipeline stage that adds a binned version of a column or columns.
If drop is set to True, the new columns retain the names of the source columns; otherwise, the resulting column gain the suffix '_bin'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bin_map |
dict
|
Maps column labels to bin arrays. The bin array is interpreted as containing start points of consecutive bins, except for the final point, assumed to be the end point of the last bin. Additionally, a bin array implicitly projects a left-most bin containing all elements smaller than the left-most end point and a right-most bin containing all elements larger that the right-most end point. For example, the list [0, 5, 8] is interpreted as the bins (-∞, 0), [0-5), [5-8) and [8, ∞). |
required |
drop |
bool, default True
|
If set to True, the source columns are dropped after being binned. |
True
|
**kwargs |
object
|
All PdPipelineStage constructor parameters are supported. |
{}
|
Examples:
>>> import pandas as pd; import pdpipe as pdp;
>>> df = pd.DataFrame([[-3],[4],[5],[9]], [1,2,3,4], ['speed'])
>>> pdp.Bin({'speed': [5]}, drop=False).apply(df)
speed speed_bin
1 -3 <5
2 4 <5
3 5 5≤
4 9 5≤
>>> pdp.Bin({'speed': [0,5,8]}, drop=False).apply(df)
speed speed_bin
1 -3 <0
2 4 0-5
3 5 5-8
4 9 8≤
Source code in pdpipe/col_generation.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 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 |
|
OneHotEncode
Bases: ColumnsBasedPipelineStage
A pipeline stage that one-hot-encodes categorical columns.
By default only k-1 dummies are created fo k categorical levels, as to avoid perfect multicollinearity between the dummy features (also called the dummy variable trap). This is done since features are usually one-hot encoded for use with linear models, which require this behaviour.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns |
single label, list-like or callable, default None
|
Column labels in the DataFrame to be encoded. If columns is None then
all the columns with object or category dtype will be converted, except
those given in the exclude_columns parameter. Alternatively,
this parameter can be assigned a callable returning an iterable of
labels from an input pandas.DataFrame. See |
None
|
dummy_na |
bool, default False
|
Add a column to indicate NaNs, if False NaNs are ignored. |
False
|
exclude_columns |
single label, list-like or callable, default None
|
Label or labels of columns to be excluded from encoding. If None then
no column is excluded. Alternatively, this parameter can be assigned a
callable returning an iterable of labels from an input
pandas.DataFrame. See |
None
|
drop_first |
bool or single label, default True
|
Whether to get k-1 dummies out of k categorical levels by removing the first level. If a non bool argument matching one of the categories is provided, the dummy column corresponding to this value is dropped instead of the first level; if it matches no category the first category will still be dropped. |
True
|
drop |
bool, default True
|
If set to True, the source columns are dropped after being encoded. |
True
|
**kwargs |
object
|
All PdPipelineStage constructor parameters are supported. |
{}
|
Examples:
>>> import pandas as pd; import pdpipe as pdp;
>>> df = pd.DataFrame([['USA'], ['UK'], ['Greece']], [1,2,3], ['Born'])
>>> pdp.OneHotEncode().apply(df)
Born_UK Born_USA
1 0 1
2 1 0
3 0 0
Source code in pdpipe/col_generation.py
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 |
|
ColumnTransformer
Bases: ColumnsBasedPipelineStage
A pipeline stage that applies transformation to dataframe columns.
This is an abstract base class for pipeline stages that apply
transformations to dataframe columns. Subclasses should implement the
_col_transform
method with the following signature:
def _col_transform( self, series: pd.Series, label: str, ) -> pd.Series: # implementation goes here
The series
argument is a pandas.Series - the column to transform. label
is the name of the column to transform. Naturally, the method must return
the new, transformed column.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns |
single label, list-like or callable
|
Column labels in the DataFrame to be transformed. Alternatively, this
parameter can be assigned a callable returning an iterable of labels
from an input pandas.DataFrame. See |
required |
result_columns |
single label or list-like, default None
|
Labels for the new columns resulting from the transformations. Must be of the same length as columns. If None, behavior depends on the drop parameter: If drop is True, then the label of the source column is used; otherwise, the provided 'suffix' is concatenated to the label of the source column. |
None
|
drop |
bool, default True
|
If set to True, source columns are dropped after being transformed. |
True
|
suffix |
str, default '_transformed'
|
The suffix transformed columns gain if no new column labels are given. |
None
|
**kwargs |
object
|
All PdPipelineStage constructor parameters are supported. |
{}
|
Source code in pdpipe/col_generation.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 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 |
|
MapColVals
Bases: ColumnTransformer
A pipeline stage that replaces the values of a column by a map.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns |
single label, list-like or callable
|
Column labels in the DataFrame to be mapped. Alternatively, this
parameter can be assigned a callable returning an iterable of labels
from an input pandas.DataFrame. See |
required |
value_map |
dict, pandas.Series, callable, str or tuple
|
The value-to-value map to use, mapping existing values to new one. If a dictionary is provided, its mapping is used. Values not in the dictionary as keys will be converted to NaN. If a Series is given, values are mapped by its index to its values. If a callable is given, it is applied element-wise to given columns. If a string is given, it is interpreted as the name of an attribute or a property of the series values to use as target values. If a tuple is provided, its first element is expected to be a string, interpreted as a name of a method of the series values to call, and its second element is expected to be a dict - possibly empty - mapping additional keyword arguments names to their values. |
required |
result_columns |
single label or list-like, default None
|
Labels for the new columns resulting from the mapping operation. Must be of the same length as columns. If None, behavior depends on the drop parameter: If drop is True, then the label of the source column is used; otherwise, the label of the source column is used with the suffix given ("_map" by default). |
None
|
drop |
bool, default True
|
If set to True, source columns are dropped after being mapped. |
True
|
suffix |
str, default '_map'
|
The suffix mapped columns gain if no new column labels are given. |
None
|
**kwargs |
object
|
All PdPipelineStage constructor parameters are supported. |
{}
|
Examples:
>>> import pandas as pd; import pdpipe as pdp;
>>> df = pd.DataFrame([[1], [3], [2]], ['UK', 'USSR', 'US'], ['Medal'])
>>> value_map = {1: 'Gold', 2: 'Silver', 3: 'Bronze'}
>>> pdp.MapColVals('Medal', value_map).apply(df)
Medal
UK Gold
USSR Bronze
US Silver
>>> from datetime import timedelta;
>>> df = pd.DataFrame(
... data=[
... [timedelta(weeks=2)],
... [timedelta(weeks=4)],
... [timedelta(weeks=10)]
... ],
... index=['proposal', 'midterm', 'finals'],
... columns=['Due'],
... )
>>> pdp.MapColVals('Due', ('total_seconds', {})).apply(df)
Due
proposal 1209600.0
midterm 2419200.0
finals 6048000.0
Source code in pdpipe/col_generation.py
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 |
|
ApplyToRows
Bases: PdPipelineStage
A pipeline stage generating columns by applying a function to each row.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func |
function
|
The function to be applied to each row of the processed DataFrame. |
required |
colname |
single label, default None
|
The label of the new column resulting from the function application. If None, 'new_col' is used. Ignored if a DataFrame is generated by the function (i.e. each row generates a Series rather than a value), in which case the label of each column in the resulting DataFrame is used. |
None
|
follow_column |
str, default None
|
Resulting columns will be inserted after this column. If None, new columns are inserted at the end of the processed DataFrame. |
None
|
func_desc |
str, default None
|
A function description of the given function; e.g. 'normalizing revenue by company size'. A default description is used if None is given. |
None
|
prec |
function, default None
|
A function taking a DataFrame, returning True if this stage is applicable to the given DataFrame. If None is given, a function always returning True is used. |
None
|
**kwargs |
object
|
All PdPipelineStage constructor parameters are supported. |
{}
|
Examples:
>>> import pandas as pd; import pdpipe as pdp;
>>> data = [[3, 2143], [10, 1321], [7, 1255]]
>>> df = pd.DataFrame(data, [1,2,3], ['years', 'avg_revenue'])
>>> total_rev = lambda row: row['years'] * row['avg_revenue']
>>> add_total_rev = pdp.ApplyToRows(total_rev, 'total_revenue')
>>> add_total_rev(df)
years avg_revenue total_revenue
1 3 2143 6429
2 10 1321 13210
3 7 1255 8785
>>> def halfer(row):
... new = {'year/2': row['years']/2, 'rev/2': row['avg_revenue']/2}
... return pd.Series(new)
>>> half_cols = pdp.ApplyToRows(halfer, follow_column='years')
>>> half_cols(df)
years rev/2 year/2 avg_revenue
1 3 1071.5 1.5 2143
2 10 660.5 5.0 1321
3 7 627.5 3.5 1255
Source code in pdpipe/col_generation.py
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 |
|
ApplyByCols
Bases: ColumnTransformer
A pipeline stage applying an element-wise function to columns.
For applying series-wise function, see AggByCols
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns |
single label, list-like or callable
|
Column labels in the DataFrame to be transformed. Alternatively, this
parameter can be assigned a callable returning an iterable of labels
from an input pandas.DataFrame. See |
required |
func |
function
|
The function to be applied to each element of the given columns. |
required |
result_columns |
str or list-like, default None
|
The names of the new columns resulting from the mapping operation. Must be of the same length as columns. If None, behavior depends on the drop parameter: If drop is True, the name of the source column is used; otherwise, the name of the source column is used with the suffix '_app'. |
None
|
drop |
bool, default True
|
If set to True, source columns are dropped after being mapped. |
True
|
func_desc |
str, default None
|
A function description of the given function; e.g. 'normalizing revenue by company size'. Optional. |
None
|
suffix |
str, default None
|
If provided, this string is concated to resulting column labels instead of '_app'. |
None
|
args |
tuple, optional
|
Positional arguments to pass to func in addition to the array/series. |
()
|
**kwargs |
dict, optional
|
Additional keyword arguments to pass as keywords arguments to func. Valid constructor parameters of superclasses are extracted and used on intialization. |
{}
|
Examples:
>>> import pandas as pd; import pdpipe as pdp; import math;
>>> data = [[3.2, "acd"], [7.2, "alk"], [12.1, "alk"]]
>>> df = pd.DataFrame(data, [1,2,3], ["ph","lbl"])
>>> round_ph = pdp.ApplyByCols("ph", math.ceil)
>>> round_ph(df)
ph lbl
1 4 acd
2 8 alk
3 13 alk
Source code in pdpipe/col_generation.py
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 |
|
ColByFrameFunc
Bases: PdPipelineStage
A pipeline stage adding a column by applying a dataframe-wide function.
Note that assigning column
with the label of an existing column and
providing the same label to the before_column
parameter will result in
replacing the original column at the same location.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
column |
str
|
The label of the resulting column. If its the label of an existing column it will replace that column. |
required |
func |
function
|
The function to be applied to the input dataframe. The function should return a pandas.Series object. |
required |
follow_column |
str, default None
|
Resulting columns will be inserted after this column. If both this
parameter and |
None
|
before_column |
str, default None
|
Resulting columns will be inserted before this column. If both this
parameter and |
None
|
func_desc |
str, default None
|
A function description of the given function; e.g. 'normalizing revenue by company size'. A default description is used if None is given. |
None
|
**kwargs |
object
|
all pdpipelinestage constructor parameters are supported. |
{}
|
Examples:
>>> import pandas as pd; import pdpipe as pdp;
>>> data = [[3, 3], [2, 4], [1, 5]]
>>> df = pd.DataFrame(data, [1,2,3], ["A","B"])
>>> func = lambda df: df['A'] == df['B']
>>> add_equal = pdp.ColByFrameFunc("A==B", func)
>>> add_equal(df)
A B A==B
1 3 3 True
2 2 4 False
3 1 5 False
Source code in pdpipe/col_generation.py
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 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 |
|
AggByCols
Bases: ColumnTransformer
A pipeline stage applying a series-wise function to columns.
For applying element-wise function, see ApplyByCols
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns |
single label, list-like or callable
|
Column labels in the DataFrame to be transformed. Alternatively, this
parameter can be assigned a callable returning an iterable of labels
from an input pandas.DataFrame. See |
required |
func |
function
|
The function to be applied to each of the given columns. Must work when given a pandas.Series object and return either a Scaler or `pandas.Series``. If a Scaler is returned, the result is broadcasted into a column of the original length. |
required |
result_columns |
str or list-like, default None
|
The names of the new columns resulting from the mapping operation. Must be of the same length as columns. If None, behavior depends on the drop parameter: If drop is True, the name of the source column is used; otherwise, the name of the source column is used with a defined suffix. |
None
|
drop |
bool, default True
|
If set to True, source columns are dropped after being mapped. |
True
|
func_desc |
str, default None
|
A function description of the given function; e.g. 'normalizing revenue by company size'. A default description is used if None is given. |
None
|
suffix |
str, optional
|
The suffix to add to resulting columns in case where results_columns is None and drop is set to False. Of not given, defaults to '_agg'. |
None
|
**kwargs |
object
|
all pdpipelinestage constructor parameters are supported. |
{}
|
Examples:
>>> import pandas as pd; import pdpipe as pdp; import numpy as np;
>>> data = [[3.2, "acd"], [7.2, "alk"], [12.1, "alk"]]
>>> df = pd.DataFrame(data, [1,2,3], ["ph","lbl"])
>>> log_ph = pdp.AggByCols("ph", np.log)
>>> log_ph(df)
ph lbl
1 1.163151 acd
2 1.974081 alk
3 2.493205 alk
>>> min_ph = pdp.AggByCols("ph", min, drop=False, suffix='_min')
>>> min_ph(df)
ph ph_min lbl
1 3.2 3.2 acd
2 7.2 3.2 alk
3 12.1 3.2 alk
Source code in pdpipe/col_generation.py
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 |
|
Log
Bases: ColumnsBasedPipelineStage
A pipeline stage that log-transforms numeric data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns |
single label, list-like or callable, default None
|
Column names in the DataFrame to be encoded. If columns is None then
all the columns with a numeric dtype will be transformed, except those
given in the exclude_columns parameter. Alternatively,
this parameter can be assigned a callable returning an iterable of
labels from an input pandas.DataFrame. See |
None
|
exclude_columns |
single label, list-like or callable, default None
|
Label or labels of columns to be excluded from encoding. If None then
no column is excluded. Alternatively, this parameter can be assigned a
callable returning an iterable of labels from an input
pandas.DataFrame. See |
None
|
drop |
bool, default False
|
If set to True, the source columns are dropped after being encoded, and the resulting encoded columns retain the names of the source columns. Otherwise, encoded columns gain the suffix '_log'. |
False
|
non_neg |
bool, default False
|
If True, each transformed column is first shifted by the smallest negative value it includes (non-negative columns are thus not shifted). |
False
|
const_shift |
int, optional
|
If given, each transformed column is first shifted by this constant. If non_neg is True then that transformation is applied first, and only then is the column shifted by this constant. |
None
|
**kwargs |
object
|
all pdpipelinestage constructor parameters are supported. |
{}
|
Examples:
>>> import pandas as pd; import pdpipe as pdp;
>>> data = [[3.2, "acd"], [7.2, "alk"], [12.1, "alk"]]
>>> df = pd.DataFrame(data, [1,2,3], ["ph","lbl"])
>>> log_stage = pdp.Log("ph", drop=True)
>>> log_stage(df)
ph lbl
1 1.163151 acd
2 1.974081 alk
3 2.493205 alk
Source code in pdpipe/col_generation.py
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 |
|