【问题标题】:Imputation of missing values for categories in pandaspandas 中类别缺失值的插补
【发布时间】:2015-12-13 14:00:44
【问题描述】:

问题是如何用 Pandas 数据框中类别列最频繁的级别填充 NaN?

在 R randomForest 包中有 na.roughfix 选项:A completed data matrix or data frame. For numeric variables, NAs are replaced with column medians. For factor variables, NAs are replaced with the most frequent levels (breaking ties at random). If object contains no NAs, it is returned unaltered.

在 Pandas 中,对于数值变量,我可以用 :

填充 NaN 值
df = df.fillna(df.median())

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    大多数情况下,您不希望所有列都采用相同的插补策略。例如,您可能需要分类变量的列模式和数字列的列均值或中位数。

    例如:

    df = pd.DataFrame({'num': [1.,2.,4.,np.nan],'cate1':['a','a','b',np.nan],'cate2':['a','b','b',np.nan]})
    
    # numeric columns
    >>> df.fillna(df.select_dtypes(include='number').mean().iloc[0], inplace=True)
    
    # categorical columns
    >>> df.fillna(df.select_dtypes(include='object').mode().iloc[0], inplace=True)
    
    >>> print(df)
    
         num cate1 cate2
     0 1.000     a     a
     1 2.000     a     b
     2 4.000     b     b
     3 2.333     a     b
    

    【讨论】:

    • 如果我们将 inplace=True 用于分类列,它不会替换缺失值。可以看看吗?
    • @Chethan,感谢您提出这个问题。您只需添加inplace=True。我已经更新了代码。
    【解决方案2】:

    在 scikit-learn up 的更新版本中,您可以使用 SimpleImputer 来估算数字和分类:

    import pandas as pd
    from sklearn.impute import SimpleImputer
    arr = [[1., 'x'], [np.nan, 'y'], [7., 'z'], [7., 'y'], [4., np.nan]]
    df1 = pd.DataFrame({'x1': [x[0] for x in arr],
                        'x2': [x[1] for x in arr]},
                      index=[l for l in 'abcde'])
    imp = SimpleImputer(missing_values=np.nan, strategy='most_frequent')
    print(pd.DataFrame(imp.fit_transform(df1),
                       columns=df1.columns,
                       index=df1.index))
    #   x1 x2
    # a  1  x
    # b  7  y
    # c  7  z
    # d  7  y
    # e  4  y
    

    【讨论】:

      【解决方案3】:

      您可以使用df = df.fillna(df['Label'].value_counts().index[0]) 用一列中出现频率最高的值填充 NaN。

      如果你想用自己最频繁的值填充每一列,你可以使用

      df = df.apply(lambda x:x.fillna(x.value_counts().index[0]))

      2018 年 25 月 10 日更新

      0.13.1 开始,pandas 包含mode 方法,用于SeriesDataframes。 您可以像这样使用它来填充每一列的缺失值(使用它自己最常见的值)

      df = df.fillna(df.mode().iloc[0])
      

      【讨论】:

      • 谢谢,它有效。我还发现我可以用 numpy np.asscalar((mode(df['Label'])[0]))
      • 对于第一种情况,df.fillna 采用 inplace 关键字,您可以将其设置为 True,这样代码会更加简洁。
      • 没想到/不知道 .iloc[0] 甚至适用于 df.mode()。虽然 df.mode() 会像 df.mean() 一样工作。谢谢!
      • 谢谢它也对我有用,但是有没有办法突出显示估算值,仅用于交叉验证。
      【解决方案4】:
      def fillna(col):
          col.fillna(col.value_counts().index[0], inplace=True)
          return col
      df=df.apply(lambda col:fillna(col))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-14
        • 2013-07-08
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 2020-02-05
        相关资源
        最近更新 更多