Loading SKLearn cancer dataset into Pandas DataFrame

Viewed 24372

I'm trying to load a sklearn.dataset, and missing a column, according to the keys (target_names, target & DESCR). I have tried various methods to include the last column, but with errors.

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

 cancer = load_breast_cancer()
 print cancer.keys()

the keys are ['target_names', 'data', 'target', 'DESCR', 'feature_names']

 data = pd.DataFrame(cancer.data, columns=[cancer.feature_names])
 print data.describe()

with the code above, it only returns 30 column, when I need 31 columns. What is the best way load scikit-learn datasets into pandas DataFrame.

6 Answers

Only target column is missing, so you can just add one.

df =  pd.DataFrame(cancer.data, columns=[cancer.feature_names])
df['target'] = cancer.target

mapping target names can be handled elegantly using map():

data["target"] = pd.Categorical(pd.Series(cancer.target).map(lambda x: cancer.target_names[x]))

As of scikit-learn 0.23 you can do the following to get a DataFrame with the target column included.

df = load_breast_cancer(as_frame=True)
df.frame
Related