【问题标题】:Missing Value detection fails for completely empty cells python pandas对于完全空的单元格 python pandas,缺失值检测失败
【发布时间】:2021-04-26 15:46:42
【问题描述】:

我创建了一个函数,其输入是 pandas 数据框。 它应该返回具有缺失值的行的行索引。 它适用于所有定义的 Missingness 值,除非单元格完全为空 - 即使我尝试在 missing_values 列表中将其指定为 [...,""]

这可能是什么问题?或者有没有更直观的方法来解决这个问题?

def missing_values(x):
    df=x

    missing_values = ["NaN","NAN","NA","Na","n/a", "na", "--","-"," ","","None","0","-inf"] #common ways to indicate missingness 
    observations = df.shape[0]  # Gives number of observations (rows)
    variables = df.shape[1] # Gives number of variables (columns)

    row_index_list = []

    #this goes through each observation in the first row 
    for n in range(0,variables): #this iterates over all variables
        column_list = [] #creates a list for each value per variable
    
        for i in range(0,observations): #now this iterates over every observation per variable
            column_list.append(df.iloc[i,n]) #and adds the values to the list

        for i in range(0,len(column_list)): #now for every value
            if column_list[i] in missing_values: #it is checked, whether the value is a Missing one 
                            row_index_list.append(column_list.index(column_list[i])) #and if yes, the row index is appended

    finished = list(set(row_index_list)) #set is used to make sure the index only appears once if there are multiple occurences in one row and then it is listed

    return finished

【问题讨论】:

    标签: python pandas missing-data


    【解决方案1】:

    可能存在虚假空白,因此请尝试在此行添加strip()

    if column_list[i].strip() in missing_values: #it is checked, whether the value is a Missing one 
    

    获取包含missing_values 的行的索引的更简单方法是使用isin()any(axis=1)

    x = x.replace('\s+', '', regex=True)
    row_index_list = x[x.isin(missing_values).any(axis=1)].index
    

    【讨论】:

      【解决方案2】:

      当您使用 read_csv 或 read_excel 将文件导入 Pandas 时,缺失的变量(字面意思是缺失)只能使用 np.nan 或其他类型的空值与 numpy 库指定。

      (对不起我的不好,我在做 np.nan == np.nan 的时候真的很傻)

      您可以先将 np.nan 值替换为:

      df = df.replace(np.nan, 'NaN')
      

      那么你的函数可以捕捉到它。

      另一种方法是在 pandas 中使用 isna(),

      df.isna()
      

      这将返回相同的 DataFrame,但单元格包含布尔值,对于每个 np.nan 单元格为 True

      如果你这样做df.isna().any()

      这将为任何包含空值的列返回一个具有 True 值的系列。

      如果要检索ID,只需将参数axis = 1添加到any()

      df.isna().any(axis = 1)
      

      这将返回一个系列,显示所有具有 np.nan 值的行。

      现在您有了指示哪一行包含空值的布尔值。如果将这些布尔值添加到列表中并将其应用于 DF.index,这将取出包含 null 的行的索引值。

      booleanlist = df.isna().any(axis =1).tolist()  
      null_row_id = df.index[booleanlist]
      

      【讨论】:

      • 记住isna 只检查实际的空值,但 OP 想要检查字符串(“NaN”、“--”、“NA”、...) isna 认为 null
      • 在这种情况下,op 可以用 np.nan 替换()他想要检查的所有值,然后按照相同的步骤进行操作
      猜你喜欢
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多