close

How to get unique values from multiple columns in a pandas groupby

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get unique values from multiple columns in a pandas groupby in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get unique values from multiple columns in a pandas groupby?

  1. How to get unique values from multiple columns in a pandas groupby?

    You can do it with apply:
    import numpy as np g = df.groupby('c')['l1','l2'].apply(lambda x: list(np.unique(x)))

  2. get unique values from multiple columns in a pandas groupby

    You can do it with apply:
    import numpy as np g = df.groupby('c')['l1','l2'].apply(lambda x: list(np.unique(x)))

Method 1

You can do it with apply:

import numpy as np
g = df.groupby('c')['l1','l2'].apply(lambda x: list(np.unique(x)))

Method 2

Alternatively, you can use agg:

g = df.groupby('c')['l1','l2'].agg(['unique'])

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read