text_html_output_1.png
from sklearn.preprocessing import LabelBinarizer

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

train = pd.read_csv('/kaggle/input/spaceship-titanic/train.csv')

train.isna().sum()

train.isna().sum()

def split_col(df, col_list, delimiter_list):
    new_df = pd.DataFrame()
    for i, col in enumerate(col_list):
        new_cols = df[col].str.split(delimiter_list[i], expand=True)
        new_cols.columns = [f'{col}_{j}' for j in range(new_cols.shape[1])]
        new_df = pd.concat([new_df, new_cols], axis=1)
    df = pd.concat([df, new_df], axis=1)
    return df

train = split_col(train, ['PassengerId', 'Cabin'], ['_', '/'])

alone = train[train.groupby('PassengerId_0').transform(len) > 1]
alone[['Cabin_0']].isnull().apply(lambda x: all(x), axis=1)
alone['Alone'] = alone[['Cabin_0']].isnull().apply(lambda x: all(x), axis=1)
train = pd.concat([train, alone['Alone']], axis=1)

train.nunique()

lb = LabelBinarizer()

def label_numeric(df, columns):
    df_lb = pd.DataFrame()
    lb = LabelBinarizer()
    for col in columns:
        if train[col].dtype == 'object':
            lb_results = lb.fit_transform(df[col])
            if len(df[col].value_counts()) == 2:
                lb_classes = [col]
            else:
                lb_classes = [f'{col}_{class_}' for class_ in lb.classes_]
            df_lb = pd.concat([df_lb, pd.DataFrame(lb_results, columns=lb_classes)], axis=1)
        elif train[col].dtype == 'float64':
            lb_classes = [col]
            df_lb = pd.concat([df_lb, pd.DataFrame(df[col], columns=lb_classes)], axis=1)
    return df_lb

train.columns

train_features = label_numeric(train, ['HomePlanet', 'CryoSleep', 'Destination', 'VIP', 'Cabin_0', 'Cabin_2', 'Alone', 'Age', 'RoomService', 'FoodCourt', 'ShoppingMall', 'Spa', 'VRDeck'])

train_features