代码之家  ›  专栏  ›  技术社区  ›  kurbielp

数据框中有多少行包含问号符号

  •  -1
  • kurbielp  · 技术社区  · 7 年前

    我有一个由csv制作的数据框,其中缺失的数据用?象征我想检查其中有多少行?发生次数为。 到目前为止,我做了这个,但它显示了所有行的数量,而不仅仅是其中的那个行?发生。

    print(sum([True for idx,row in df.iterrows() if 
    any(row.str.contains('[?]'))]))
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   cs95 abhishek58g    7 年前

    您可以使用 apply + str.contains ,假设所有列都是字符串。

    c = np.sum(df.apply(lambda x: x.str.contains('\?')).values)
    

    如果只需要选择字符串列,请使用 select_dtypes -

    i = df.select_dtypes(exclude=['number']).apply(lambda x: x.str.contains('\?')) 
    c = np.sum(i.values)
    

    或者,查找 数字 包含的行数 ? 在其中,使用

    c = df.apply(lambda x: x.str.contains('\?')).any(axis=1).sum()
    

    演示-

    df
    
          A      B
    0   aaa   ?xyz
    1   bbb  que!?
    2     ?    ddd
    3  foo?    fff
    
    df.apply(lambda x: x.str.contains('\?')).any(1).sum()
    4