text_plain_output_1.png image_output_1.png
import numpy as np

import pandas as pd

df = pd.read_csv('../input/train.csv', index_col='PassengerId')

df.dropna().describe()

ages_mean = df.pivot_table('Age', index=['Title'], columns=['Sex', 'Pclass'], aggfunc='mean')
ages_mean

ages_std = df.pivot_table('Age', index=['Title'], columns=['Sex', 'Pclass'], aggfunc='std')
ages_std

def age_guesser(person):
    gender = person['Sex']
    mean_age = ages_mean[gender].loc[person['Title'], person['Pclass']]
    std = ages_std[gender].loc[person['Title'], person['Pclass']]
    persons_age = np.random.randint(mean_age - std, mean_age + std)
    return persons_age
unknown_age = df['Age'].isnull()
people_w_unknown_age = df.loc[unknown_age, ['Age', 'Title', 'Sex', 'Pclass']]
people_w_unknown_age['Age'] = people_w_unknown_age.apply(age_guesser, axis=1)
people_w_unknown_age.head(10)