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

需要确定组在pandas数据框中是否只包含一个类别

  •  0
  • james  · 技术社区  · 6 年前

    我现在有一个id和一个名为“childOrParent”的列的数据框。 一个群体不能没有父母就有孩子。

    +----+---------------+
    | id | childOrParent |
    +----+---------------+
    |  1 | Parent        |
    |  1 | child         |
    |  2 | Parent        |
    |  3 | child         |
    |  3 | child         |
    |  3 | Parent        |
    +----+---------------+
    

    如何检查数据帧是否有效?如果有一个身份证组只有孩子,那么我需要知道这个身份证。

    ex)以下数据帧将无效 我需要知道 编号:3

    +----+---------------+
    | id | childOrParent |
    +----+---------------+
    |  1 | Parent        |
    |  1 | child         |
    |  2 | Parent        |
    |  3 | child         |
    |  3 | child         |
    |  3 | child         |
    +----+---------------+
    

    我试图只获取一个组中的子级或父级的计数,然后合并这两个数据帧,但这似乎不对。

    1 回复  |  直到 6 年前
        1
  •  2
  •   BENY    6 年前

    使用 groupby 具有 filter + all

    df.groupby('id').filter(lambda x : (x['childOrParent']=='child').all())
    Out[383]: 
       id childOrParent
    3   3         child
    4   3         child
    5   3         child
    df.groupby('id').filter(lambda x : (x['childOrParent']=='child').all()).id.unique()
    Out[384]: array([3], dtype=int64)