.groupby & .fillna with median

后端 未结 2 1058
南笙
南笙 2021-01-25 06:30
# Create a groupby object: by_sex_class
by_sex_class = titanic.groupby([\"sex\",\"pclass\"]).count()

# Write a function that imputes median
def impute_median(series):
          


        
相关标签:
2条回答
  • 2021-01-25 07:17

    The new values are matched to the original dataframe by the index (when you group, you still keep the original index).

    df['age'] = df.groupby(["sex","pclass"])['age'].transform(lambda x: x.fillna(x.median()))
    
    0 讨论(0)
  • 2021-01-25 07:23

    I will recommend using this

    df['age'].fillna(df.groupby(["sex","pclass"])['age'].transform('median'),inplace=True)
    
    0 讨论(0)
提交回复
热议问题