将sklearn数据框转换为Pandas数据框,并保留分类标签

时间:2019-11-18 14:07:33

标签: python pandas dataframe scikit-learn

我正在使用sklearn导入数据:

from sklearn import datasets
dataset = datasets.fetch_openml('credit-g', version = 'active')

sklearn可以将分类数据转换为数字。

enter image description here

现在我想将此数据集转换为Pandas DataFrame:

data = pd.DataFrame(dataset.data, columns = dataset.feature_names)
data['class'] = pd.Series(dataset.target)

但是此命令会删除所有分类数据-它们现在是数字。

enter image description here

我想要的是在转换后将原始文本标签替换为数字的数据框。因此,从sklearn数据框转换为熊猫数据框后,数据看起来应该相同,就像我只是使用以下命令下载了该数据一样:

pd.read_csv("https://www.openml.org/data/get_csv/31/dataset_31_credit-g.arff")

enter image description here

有可能吗?

1 个答案:

答案 0 :(得分:1)

根据fetch_openml的文档,返回的字典包含:

[...]
data : np.array or scipy.sparse.csr_matrix of floats
    The feature matrix. Categorical features are encoded as ordinals.
[...]
categories : dict
    Maps each categorical feature name to a list of values, such that the value
    encoded as i is ith in the list.
[...]

没有选项可以不对分类特征进行编码。只要您将使用sklearn来下载数据集,就会有浮点数而不是字符串。

但是,由于还返回了类别,因此您可以使用以下分类功能重建具有分类特征的“基础”数据集(我不确定这是最快的解决方案,还是更优雅的解决方案):

from sklearn import datasets
import pandas as pd
import numpy as np

def main():
    dataset = datasets.fetch_openml('credit-g', version = 'active')

    raws = [
        np.take(dataset['categories'][feature], dataset['data'][:,i].astype(int))  # Take string value for categorical features
        if feature in dataset['categories'] else dataset['data'][:,i]  # Else use the floats as is
        for i, feature in enumerate(dataset['feature_names'])
    ]

    data = pd.DataFrame(np.stack(raws, axis=1), columns=dataset.feature_names)
    data['class'] = pd.Series(dataset.target)
    print("Initial dtypes:")
    print(data.dtypes)

    dtypes = {
        f: 'category' if f in dataset['categories'] else 'float'
        for f in dataset['feature_names']
    }
    dtypes['class'] = 'category'
    data = data.astype(dtypes)
    print("\nFirst cast:")
    print(data.dtypes)

    int_cols = [1, 4, 12]
    data.iloc[:, int_cols] = data.iloc[:, int_cols].astype('int64')
    print("\nInt cast:")
    print(data.dtypes)

if __name__ == '__main__':
    main()