如何在熊猫中使用分组模式替换缺失值?

发布于 2021-01-29 15:00:44

我按照该方法在这个职位跟团模式,以取代缺失值,但遇到“IndexError:索引越界”。

 df['SIC'] = df.groupby('CIK').SIC.apply(lambda x: x.fillna(x.mode()[0]))

我想这可能是因为某些组缺少所有值并且没有模式。有办法解决这个问题吗?谢谢!

关注者
0
被浏览
62
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    mode鉴于确实没有任何商定的方式来处理关系,所以这非常困难。另外,它通常非常慢。这是一种“快速”的方法。我们将定义一个函数来计算每个组的模式,然后用来填充缺失的值map。我们不会遇到缺少组的问题,尽管对于关系,我们可以随意选择排序时首先出现的模式值:

    def fast_mode(df, key_cols, value_col):
        """ 
        Calculate a column mode, by group, ignoring null values.
    
        Parameters
        ----------
        df : pandas.DataFrame
            DataFrame over which to calcualate the mode. 
        key_cols : list of str
            Columns to groupby for calculation of mode.
        value_col : str
            Column for which to calculate the mode.
    
        Return
        ------ 
        pandas.DataFrame
            One row for the mode of value_col per key_cols group. If ties, 
            returns the one which is sorted first. 
        """
        return (df.groupby(key_cols + [value_col]).size() 
                  .to_frame('counts').reset_index() 
                  .sort_values('counts', ascending=False) 
                  .drop_duplicates(subset=key_cols)).drop(columns='counts')
    

    样本数据df

       CIK  SIK
    0    C  2.0
    1    C  1.0
    2    B  NaN
    3    B  3.0
    4    A  NaN
    5    A  3.0
    6    C  NaN
    7    B  NaN
    8    C  1.0
    9    A  2.0
    10   D  NaN
    11   D  NaN
    12   D  NaN
    

    码:

    df.loc[df.SIK.isnull(), 'SIK'] = df.CIK.map(fast_mode(df, ['CIK'], 'SIK').set_index('CIK').SIK)
    

    输出df

       CIK  SIK
    0    C  2.0
    1    C  1.0
    2    B  3.0
    3    B  3.0
    4    A  2.0
    5    A  3.0
    6    C  1.0
    7    B  3.0
    8    C  1.0
    9    A  2.0
    10   D  NaN
    11   D  NaN
    12   D  NaN
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看