# Python how to add a condition to the groupby while calculating the median of a field?

I need to add a new condition to the following line:

train["Age"].fillna(train.groupby("Ticket")["Age"].transform("median"), inplace=True)


Currently, its taking the median of the age based on tickets class.

I need to add to this groupby("Ticket") another condition, where train["PrSb"]==0.

## 1 Answer

This should work:

train["Age"].fillna(train.loc[train["PrSb"] == 0].groupby("Ticket")["Age"].transform("median"), inplace=True)


This adds an extra rowwise filter to the dataframe that is used in the groupby operation, which only selects rows where the PrSb colum is equal to 0.