如何根据数据框的条件选择列中缺少值的行?

时间:2019-09-09 03:59:59

标签: pandas

我有一个从Excel工作表中提取的数据框。

我要查找不合法的行。

合法行满足以下任一条件:

  1. 恰好填充了1列,但其他列为空或为空
  2. 恰好填充了2列,但其他列为空或为空
  3. 完全填充了8列

因此,非合法行与上述内容相反,例如:

  1. 填充了8列中的7列,但其中一列是空的
  2. 8列中的6列已填写,但两列中的任何一个都为空 等等...

我感兴趣的8列是:A,B,D,E,F,G,I,L列。

我只想返回那些不合法的行。

我知道如何查找特定列中为空的行,但不确定如何根据上述条件查找不合法的行。

    empty_A = sheet[sheet[sheet.columns[0]].isnull()]
    empty_B = sheet[sheet[sheet.columns[1]].isnull()]
    empty_D = sheet[sheet[sheet.columns[3]].isnull()]
    empty_E = sheet[sheet[sheet.columns[4]].isnull()]
    empty_F = sheet[sheet[sheet.columns[5]].isnull()]
    empty_G = sheet[sheet[sheet.columns[6]].isnull()]
    empty_I = sheet[sheet[sheet.columns[8]].isnull()]
    empty_L = sheet[sheet[sheet.columns[11]].isnull()]
    print(empty_G)

更新:

我使用list comprehension

解决了

3 个答案:

答案 0 :(得分:0)

df.loc[(df.isna().sum(axis=1)==0) | (df.isna().sum(axis=1)==7) | (df.isna().sum(axis=1)==6)]

答案 1 :(得分:0)

如果您已经填充了数据框,则可以这样做

jupyter notebook

答案 2 :(得分:0)

似乎您想计算这8个特定列中的空值数量,并根据找到的空值选择行。该措辞建议根据总和进行选择。大多数熊猫操作默认执行列式操作,因此您需要将sum()告诉perform the sum for each row by using axis="columns",如下所示:

# This is a series indexed like df.
# It counts the number of null values in the given columns.
n_null = df[["A", "B", "D", "E", "F", "G", "I", "L"]].isnull().sum(axis="columns")

# This selects the rows where n_null has certain values.
df_notlegit = df.loc[n_null.isin([8, 5, 4, 3, 2])]

# This is another way to do it.
df_nonlegit = df.loc[(n_null > 1) & (n_null < 9)]