text_plain_output_1.png image_output_1.png
from sklearn.preprocessing import OneHotEncoder

import pandas as pd

import seaborn as sns

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

def wrangle(df):
    df['Male'] = df['Sex'].map(lambda x: x == 'male')
    df['Pronoun'] = df['Name'].map(lambda x: x.split(', ')[1].split('.')[0])
    df['Prefix'] = df['Ticket'].map(lambda x: x.split(' ')[0].split('/')[0].replace('.', '') if ' ' in x else '')
    df['Letter'] = df['Cabin'].fillna('00').map(lambda x: x[0])
    df['Family'] = df['SibSp'] + df['Parch']
    df = df.drop(['PassengerId', 'Name', 'Ticket', 'Sex', 'Cabin'], axis=1)
    return df

def encode(X_train, X_test, cat_cols):
    encoder = OneHotEncoder(categories='auto', sparse=False, handle_unknown='ignore')
    encoder.fit(X_train[cat_cols])
    X_train_encoded = encoder.transform(X_train[cat_cols])
    X_train_final = pd.concat([X_train.drop(cat_cols, axis=1), pd.DataFrame(X_train_encoded, index=X_train.index)], axis=1)
    X_test_encoded = encoder.transform(X_test[cat_cols])
    X_test_final = pd.concat([X_test.drop(cat_cols, axis=1), pd.DataFrame(X_test_encoded, index=X_test.index)], axis=1)
    return (X_train_final, X_test_final, encoder)

new_train = wrangle(train)

sns.set(style='whitegrid')
sns.despine(left=True)

new_train['AgeGroup'] = pd.cut(new_train['Age'], bins=[0, 10, 20, 30, 40, 50, 60, 70, 80])
age_survival = new_train.groupby(['AgeGroup'])['Survived'].mean().reset_index()
sns.barplot(x='AgeGroup', y='Survived', data=age_survival)
plt.title('Survival Rate by Age Group')
plt.xlabel('Age Group')
plt.ylabel('Survival Rate')
plt.show()