<jupyter_start><jupyter_text>Target mean encoding with pandas<jupyter_code>X_train.groupby(['A7'])['A16'].mean().plot()
plt.title('Relationship between A7 and the target')
plt.ylabel('Mean of target')
plt.show()
# let's create a dictionary with the target mean per category
# for the variable A7

ordered_labels = X_train.groupby(['A7'])['A16'].mean().to_dict()

ordered_labels
# replace the labels with the target mean

X_train['A7'] = X_train['A7'].map(ordered_labels)
X_test['A7'] = X_test['A7'].map(ordered_labels)
# let's inspect the result

X_train['A7'].head()
X_train.groupby(['A7'])['A16'].mean().plot()
plt.title('Relationship between A7 and the target')
plt.ylabel('Mean of target')
plt.show()<jupyter_output><empty_output><jupyter_text>Target mean encoding with Feature-Engine<jupyter_code>X_train, X_test, y_train, y_test = train_test_split(
    data.drop(labels=['A16'], axis=1),  # predictors
    data['A16'],  # target
    test_size=0.3,  # percentage of obs in test set
    random_state=0)  # seed to ensure reproducibility
# let's create the encoder

mean_enc = MeanCategoricalEncoder(variables=None)
# when fitting the transformer, we need to pass the target as well
# just like with any Scikit-learn predictor class

mean_enc.fit(X_train, y_train)
# variables that will be encoded

mean_enc.variables
# in the encoder dict we can observe the target mean per category
# per variable

mean_enc.encoder_dict_
# let's transform train and test set

X_train_enc = mean_enc.transform(X_train)
X_test_enc = mean_enc.transform(X_test)
X_train_enc.head()
X_test_enc.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12344913151364764, 'fraction_numerical': 0.015508684863523574, 'mean_word_length': 6.200892857142857, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '114419', 'license': 'MIT', 'n_tokens_mistral': 573, 'n_tokens_neox': 546, 'n_words': 144, 'path': 'Chapter03/Recipe-6-target-mean-encoding.ipynb', 'repo_name': 'paulorobertolds/Python-Feature-Engineering-Cookbook', 'size': '1612'}