【问题标题】:Fill NaNs in pandas columns using mean for numeric dtype, mode for non-numeric dtype使用数字 dtype 的均值填充 pandas 列中的 NaN,非数字 dtype 的模式
【发布时间】:2020-10-24 15:57:03
【问题描述】:
    # handling missing values
    class handling_missing_data():
    
      # Imputation
      # Handling columns which have null values
      
      for col in df[:]:
        if ():
    
          if (pd.df[:].astype(pd.Series([np.integer]))):
    
            df = df.select_dtypes(include=[np.integer]).fillna(df.select_dtypes(include=[np.integer]).mean().iloc[0], inplace=True)
      
          elif (pd.df[:].astype(pd.Series([object, str]))):
            
            df = df.select_dtypes(include=['object', 'str']).fillna(df.select_dtypes(include=['object', 'str']).mode().iloc[0], inplace=True)
      
      print(df.head())

为什么此代码不起作用,因为我试图识别特定列中数据集中的缺失值,并通过使用循环根据列数据类型使用平均值填充缺失的列值。我正在寻找一些通用的方法。

【问题讨论】:

    标签: python pandas dataframe data-science


    【解决方案1】:

    你的代码有太多错误,无法合理地回答,所以让我告诉你我会怎么做。

    # Select numeric columns.
    a = df.select_dtypes('number')
    # Select string and object columns.
    b = df.select_dtypes('object')
    
    # Fill numeric columns with mean.
    df[a.columns] = a.fillna(a.mean())
    # Fill object columns with mode.
    df[b.columns] = b.fillna(b.agg(lambda x: x.mode().values[0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-30
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 2014-02-12
      相关资源
      最近更新 更多