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

PADAS数据帧组检查列的唯一值数目是否为1,但不包括空字符串

  •  1
  • daiyue  · 技术社区  · 6 年前

    我有以下内容 df ,

    id    invoice_no
    1     6636
    1     6637
    2     6639
    2     6639
    3     
    3    
    4     6635
    4     6635
    4     6635
    

    这个 invoice_no 对于 id 3都是空字符串或空格;我想

    df['same_invoice_no'] = df.groupby("id")["invoice_no"].transform('nunique') == 1
    

    但也要考虑空格和空字符串 发票号码 在每组中 same_invoice_no = False 我在想怎么做。结果是,

    id    invoice_no    same_invoice_no
    1     6636          False
    1     6637          False
    2     6639          True
    2     6639          True
    3                   False
    3                   False
    4     6635          True
    4     6635          True
    4     6635          True
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Vaishali    6 年前

    空字符串等于“真”,但Nan不等于“真”。将空字符串替换为numpy Nan

    df.replace('', np.nan, inplace = True)
    df['same_invoice_no'] = df.groupby("id")["invoice_no"].transform('nunique') == 1
    
        id  invoice_no  same_invoice_no
    0   1   6636.0      False
    1   1   6637.0      False
    2   2   6639.0      True
    3   2   6639.0      True
    4   3   NaN         False
    5   3   NaN         False
    6   4   6635.0      True
    7   4   6635.0      True
    8   4   6635.0      True