python - 如何在 Pandas 中用分组模式替换缺失值?

标签 python pandas missing-data imputation

我按照this post中的方法进行操作用分组模式替换缺失值,却遇到“IndexError:索引超出范围”。

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

我猜这可能是因为某些组具有所有缺失值并且没有众数。有办法解决这个问题吗?谢谢你!

最佳答案

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

关于python - 如何在 Pandas 中用分组模式替换缺失值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562696/

相关文章:

python - 使用Python中的Turtle模块将缩小的 turtle 向上移动窗口屏幕

python - 如何使用先前的滚动平均值填充 pandas 数据框中的后续空值?

python - 每个单词之间的空格数

Python Tkinter :removing widgets that were created using a for loop

python - 如何将模糊函数与 apply(lambda x : ) function?

python - 如何将具有重复值的新列插入到 pandas 表中?

Java SE 开发工具包没有安装对吗?

julia - 参数错误: quantiles are undefined in presence of NaNs or missing values

c++ - 使用(python,perl)(linux)在excel中创建图表

python - 仅更新到期日期大于 python 最大日期 - 2261 - 无法将浮点 NaN 转换为整数的行