代码之家  ›  专栏  ›  技术社区  ›  as - if

列名和计数为空的值的打印/警告

  •  1
  • as - if  · 技术社区  · 8 年前

    我有一个数据帧,它有几个列,这些列有空值。目前我正在做以下工作:

    import warnings
    if df.columns[df.isnull().any()].any(): 
         warnings.warn("Found Null Value on column: " + str(df[df.columns[df.isnull().any()]].isnull().sum()))
    

    打印出以下内容

    UserWarning: Found Null Value on column: qty    50
    dtype: int64
    

    我想要一些像

    UserWarning: Found Null Value on column: qty    count: 50
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   jpp    8 年前

    使用f字符串,在python 3.6+中提供。也可以使用 str.format . 而不是检查 pd.Series.any ,我们可以简单地测试 nulls_sum 为非零。

    df = pd.DataFrame([[0, np.nan, 1], [np.nan, 2, 3]])
    
    import warnings
    
    for col in df.columns:
        nulls_sum = df[col].isnull().sum()
        if nulls_sum:
            warnings.warn(f"Found Null Value on column: {col}, count: {nulls_sum}")
    
    UserWarning: Found Null Value on column: 0, count: 1
    UserWarning: Found Null Value on column: 1, count: 1