DatetimeSubtraction#

class feature_engine.datetime.DatetimeSubtraction(variables=None, reference=None, new_variables_names=None, output_unit='D', missing_values='ignore', drop_original=False, dayfirst=False, yearfirst=False, utc=None, format=None)[source]#

DatetimeSubtraction() applies datetime subtraction between a group of datetime variables and one or more datetime features, adding the resulting variables to the dataframe.

DatetimeSubtraction() works with variables cast as datetime or object. It subtracts the variables listed in the parameter reference from those listed in the parameter variables.

More details in the User Guide.

Parameters
variables: list

The list of datetime variables that the reference variables will be subtracted from (left side of the subtraction operation).

reference: list

The list of datetime reference variables that will be subtracted from variables (right side of the subtraction operation).

new_variables_names: list, default=None

Names of the new variables. You have the option to pass a list with the names you’d like to assing to the new variables. If None, the transformer will assign arbitrary names.

output_unit: string, default=’D’

The string representation of the output unit of the datetime differences. The default is D for day. This parameter is passed to numpy.timedelta64. Other possible values are Y for year, M for month, W for week, h for hour, m for minute, s for second, ms for millisecond, us or μs for microsecond, ns for nanosecond, ps for picosecond, fs for femtosecond and as for attosecond.

missing_values: string, default=’raise’

Indicates if missing values should be ignored or raised. If 'raise' the transformer will return an error if the the datasets to fit or transform contain missing values. If 'ignore', missing data will be ignored when learning parameters or performing the transformation.

drop_original: bool, default=”False”

If True, the variables listed in variables and reference will be dropped from the dataframe after the computation of the new features.

dayfirst: bool, default=”False”

Specify a date parse order if arg is str or is list-like. If True, parses dates with the day first, e.g. 10/11/12 is parsed as 2012-11-10. Same as in pandas.to_datetime.

yearfirst: bool, default=”False”

Specify a date parse order if arg is str or is list-like. Same as in pandas.to_datetime.

  • If True parses dates with the year first, e.g. 10/11/12 is parsed as 2010-11-12.

  • If both dayfirst and yearfirst are True, yearfirst is preceded.

utc: bool, default=None

Return UTC DatetimeIndex if True (converting any tz-aware datetime.datetime objects as well). Same as in pandas.to_datetime.

format: str, default None

The strftime to parse time, e.g. “%d/%m/%Y”. Check pandas to_datetime() for more information on choices. If you have variables with different formats pass “mixed”, to infer the format for each element individually. This is risky, and you should probably use it along with dayfirst, according to pandas’ documentation.

Attributes
variables_:

The list with datetime variables from which the variables in reference will be substracted. It is created after the transformer corroborates that the variables in variables are, or can be parsed to datetime.

reference_:

The list with the datetime variables that will be subtracted from variables_. It is created after the transformer corroborates that the variables in reference are, or can be parsed to datetime.

feature_names_in_:

List with the names of features seen during fit.

n_features_in_:

The number of features in the train set used in fit.

Examples

>>> import pandas as pd
>>> from feature_engine.datetime import DatetimeSubtraction
>>> X = pd.DataFrame({
>>>     "date1": ["2022-09-18", "2022-10-27", "2022-12-24"],
>>>     "date2": ["2022-08-18", "2022-08-27", "2022-06-24"]})
>>> dtf = DatetimeSubtraction(variables=["date1"], reference=["date2"])
>>> dtf.fit(X)
>>> dtf.transform(X)
        date1       date2  date1_sub_date2
0  2022-09-18  2022-08-18             31.0
1  2022-10-27  2022-08-27             61.0
2  2022-12-24  2022-06-24            183.0

Methods

fit:

This transformer does not learn parameters.

fit_transform:

Fit to data, then transform it.

get_feature_names_out:

Get output feature names for transformation.

get_params:

Get parameters for this estimator.

set_params:

Set the parameters of this estimator.

transform:

Create new features.

fit(X, y=None)[source]#

This transformer does not learn any parameter.

Parameters
X: pandas dataframe of shape = [n_samples, n_features]

The training input samples. Can be the entire dataframe, not just the variables to transform.

y: pandas Series, or np.array. Default=None.

It is not needed in this transformer. You can pass y or None.

fit_transform(X, y=None, **fit_params)[source]#

Fit to data, then transform it.

Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.

Parameters
Xarray-like of shape (n_samples, n_features)

Input samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).

**fit_paramsdict

Additional fit parameters.

Returns
X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_feature_names_out(input_features=None)[source]#

Get output feature names for transformation. In other words, returns the variable names of transformed dataframe.

Parameters
input_featuresarray or list, default=None

This parameter exits only for compatibility with the Scikit-learn pipeline.

  • If None, then feature_names_in_ is used as feature names in.

  • If an array or list, then input_features must match feature_names_in_.

Returns
feature_names_out: list

Transformed feature names.

rtype

List[Union[str, int]] ..

get_metadata_routing()[source]#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns
routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_params(deep=True)[source]#

Get parameters for this estimator.

Parameters
deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns
paramsdict

Parameter names mapped to their values.

set_params(**params)[source]#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters
**paramsdict

Estimator parameters.

Returns
selfestimator instance

Estimator instance.

transform(X)[source]#

Add new features.

Parameters
X: pandas dataframe of shape = [n_samples, n_features]

The data to transform.

Returns
X_new: Pandas dataframe

The input dataframe plus the new variables.

rtype

DataFrame ..