【问题标题】:Fill missing values with the most common value in the grouped form用分组表格中最常见的值填充缺失值
【发布时间】:2021-01-29 16:47:57
【问题描述】:

谁能帮我用最常见的值但分组的形式填充缺失值? .这里我想用相同型号的汽车填充圆柱列的缺失值。

我试过这个:

sh_cars['cylinders']=sh_cars['cylinders'].fillna(sh_cars.groupby('model')['cylinders'].agg(pd.Series.mode))

还有其他的,但我每次都收到错误消息。

提前致谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为问题是每个(或所有)组只有NaNs,因此会引发错误。可能的解决方案是使用带有GroupBy.transform 的自定义函数来返回与原始DataFrame 相同大小的系列:

    data = {'model':['a','a','a','a','b','b','a'], 
            'cylinders':[2,9,9,np.nan,np.nan,np.nan,np.nan]}
    
    sh_cars = pd.DataFrame(data) 
    
    f = lambda x: x.mode().iat[0] if x.notna().any() else np.nan
    s = sh_cars.groupby('model')['cylinders'].transform(f)
    sh_cars['new']=sh_cars['cylinders'].fillna(s)
    print (sh_cars)
      model  cylinders  new
    0     a        2.0  2.0
    1     a        9.0  9.0
    2     a        9.0  9.0
    3     a        NaN  9.0
    4     b        NaN  NaN
    5     b        NaN  NaN
    6     a        NaN  9.0
    

    替换原来的列:

    f = lambda x: x.mode().iat[0] if x.notna().any() else np.nan
    s = sh_cars.groupby('model')['cylinders'].transform(f)
    sh_cars['cylinders']=sh_cars['cylinders'].fillna(s)
    print (sh_cars)
      model  cylinders
    0     a        2.0
    1     a        9.0
    2     a        9.0
    3     a        9.0
    4     b        NaN
    5     b        NaN
    6     a        9.0
    

    【讨论】:

    • 另外(我个人的用例),你也可以很容易地替换其他值(例如2.0),只需执行sh_cars['cylinders'] = s
    猜你喜欢
    • 2016-08-26
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多