1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Get rows with unique value in a specific column in pandas

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    Following is my data frame.


    id name class
    --------------------------
    0 Nick a
    1 Jane b
    2 Jacon a
    3 Jack b
    4 Cooze a
    --------------------------
    5 Nick b
    6 Jane b
    7 Jacon c
    8 Jack a
    9 Cooze a


    I need to get all names that have unique value in class column, i.e.:

    id name class count
    -----------------------------------
    0 Jane b 2
    1 Cooze a 2


    What I have done:

    data = {'name':['Nick', 'Jane', 'Jacon', 'Jack', 'Cooze', 'Nick', 'Jane', 'Jacon', 'Jack', 'Cooze'],
    'class':['a', 'b', 'a', 'b', 'a', 'b', 'b', 'c', 'a', 'a']}

    df = pd.DataFrame(data)
    new_data = df.groupby('name')['class'].unique()
    print(new_data)


    What I get is:

    name
    Jacon [a]
    Jane [a, b]
    jack [b, a]
    krish [a, c]
    nick
    Name: class, dtype: object



    In next step I have to get the length of objects in column class, and return the ones that are 1. But first I get different errors when I try to get the length of objects in the second column and second, I have the feeling it must be easier than this! I am very beginner in pandas, does anyone know how can I get it? Thank you in advance.

    Continue reading...

Compartilhe esta Página