python - 将 ColumnTransformer() 结果附加到管道中的原始数据?

标签 python pandas scikit-learn pipeline

这是我的输入数据:

enter image description here

这是所需的输出,其中对列 r、f 和 m 进行了转换,并将结果附加到原始数据

enter image description here

这是代码:

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import PowerTransformer    

df = pd.DataFrame(np.random.randint(0,100,size=(10, 3)), columns=list('rfm'))
column_trans = ColumnTransformer(
    [('r_std', StandardScaler(), ['r']),
     ('f_std', StandardScaler(), ['f']),
     ('m_std', StandardScaler(), ['m']),
     ('r_boxcox', PowerTransformer(method='box-cox'), ['r']),
     ('f_boxcox', PowerTransformer(method='box-cox'), ['f']),
     ('m_boxcox', PowerTransformer(method='box-cox'), ['m']),
    ])

transformed = column_trans.fit_transform(df)
new_cols = ['r_std', 'f_std', 'm_std', 'r_boxcox', 'f_boxcox', 'm_boxcox']

transformed_df = pd.DataFrame(transformed, columns=new_cols)
pd.concat([df, transformed_df], axis = 1)

我还需要额外的转换器,所以我需要将原始列保留在管道中。有没有更好的方法来处理这个问题?特别是在管道中进行串联和列命名?

最佳答案

一种方法是使用一个虚拟转换器,它只返回转换后的列及其原始值:

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import PowerTransformer    

np.random.seed(1714)

class NoTransformer(BaseEstimator, TransformerMixin):
    def fit(self, X, y=None):
        return self

    def transform(self, X):
        assert isinstance(X, pd.DataFrame)
        return X

我正在向数据集中添加一个 id 列,以便我可以在 ColumnTransformer() 中展示剩余参数的使用,我觉得这非常有用。
df = pd.DataFrame(np.hstack((np.arange(10).reshape((10, 1)),
                             np.random.randint(1,100,size=(10, 3)))),
                  columns=["id"] + list('rfm'))

使用带值传递的余数(默认值为 drop)可以保留未转换的列;来自 docs

使用 NoTransformer() 虚拟类,我们可以将列 'r'、'f'、'm' 转换为具有相同的值。
column_trans = ColumnTransformer(
    [('r_original', NoTransformer(), ['r']),
     ('f_original', NoTransformer(), ['f']),
     ('m_original', NoTransformer(), ['m']),
     ('r_std', StandardScaler(), ['r']),
     ('f_std', StandardScaler(), ['f']),
     ('m_std', StandardScaler(), ['m']),
     ('r_boxcox', PowerTransformer(method='box-cox'), ['r']),
     ('f_boxcox', PowerTransformer(method='box-cox'), ['f']),
     ('m_boxcox', PowerTransformer(method='box-cox'), ['m']),
    ], remainder="passthrough")


如果你想转换更多的列,一个提示:拟合的 ColumnTransformer() 类(在你的例子中是 column_trans)有一个 Transformers_ 方法,可以让你以编程方式访问名称 ['r_std', 'f_std', 'm_std', 'r_boxcox', 'f_boxcox', 'm_boxcox']:
column_trans.transformers_

#[('r_original', NoTransformer(), ['r']),
# ('f_original', NoTransformer(), ['f']),
# ('m_original', NoTransformer(), ['m']),
# ('r_std', StandardScaler(copy=True, with_mean=True, with_std=True), ['r']),
# ('f_std', StandardScaler(copy=True, with_mean=True, with_std=True), ['f']),
# ('m_std', StandardScaler(copy=True, with_mean=True, with_std=True), ['m']),
# ('r_boxcox',
#  PowerTransformer(copy=True, method='box-cox', standardize=True),
#  ['r']),
# ('f_boxcox',
#  PowerTransformer(copy=True, method='box-cox', standardize=True),
#  ['f']),
# ('m_boxcox',
#  PowerTransformer(copy=True, method='box-cox', standardize=True),
#  ['m']),
# ('remainder', 'passthrough', [0])]



最后,我认为您的代码可以这样简化:
column_trans_2 = ColumnTransformer(
    ([
     ('original', NoTransformer(), ['r', 'f', 'm']),
     ('std', StandardScaler(), ['r', 'f', 'm']),
     ('boxcox', PowerTransformer(method='box-cox'), ['r', 'f', 'm']),
    ]), remainder="passthrough")

transformed_2 = column_trans_2.fit_transform(df)
column_trans_2.transformers_

#[('std',
#  StandardScaler(copy=True, with_mean=True, with_std=True),
#  ['r', 'f', 'm']),
# ('boxcox',
#  PowerTransformer(copy=True, method='box-cox', standardize=True),
#  ['r', 'f', 'm'])]


并通过transformers_以编程方式分配列名:
new_col_names = []
for i in range(len(column_trans_2.transformers)):
    new_col_names += [column_trans_2.transformers[i][0] + '_' + s for s in column_trans_2.transformers[i][2]]
# The non-transformed columns ('id' in this case) will be appended on the right of
# the array and do not show up in the 'transformers_' method.
# Add the id columns to the col_names manually
new_col_names += ['id']

# ['original_r', 'original_f', 'original_m', 'std_r', 'std_f', 'std_m', 'boxcox_r',
#  'boxcox_f', 'boxcox_m', 'id']


pd.DataFrame(transformed_2, columns=new_col_names)

关于python - 将 ColumnTransformer() 结果附加到管道中的原始数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592115/

相关文章:

python - 使用 sklearn.utils.resample 带分层和不带分层的区别

python - 将 PyTorch 张量与 scikit-learn 结合使用

python - [[...]] 在 python 中是什么意思?

python - 为什么我在pandas中groupby后得到 'key error'?

python - 删除 Python Pandas 中多列中的所有重复行

python - 使用 python 的文本文件标题中的条目列表

Python 在 pandas csv reader 中解压缩 gzip csv

python - numpy:对多维数组进行操作

python - 你可以在 vim 中对视觉选择的文本执行什么?

python - scikit-learn intersphinx 链接/库存对象?