I am working on the Titanic dataset and there are null values in the Age column. I would like to fill them in based on there Pclass.

For example, if class is 1, I will fill with the mean of all passengers whose class is 1. I have found all the means, but I cannot figure out how to fill age column with conditions.

  • 1
    $\begingroup$ please provide with the snapshot or link to the dataset $\endgroup$ Commented Nov 13, 2021 at 18:28

1 Answer 1



df['Age'] = df['Age'].fillna(df.groupby('Pclass')['Age'].transform('mean'))


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.