Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find the unique values of a dataframe and return in a dataframe form

I have the following data frame

df = pd.DataFrame({'fruits': ['orange', 'mango', 'apple', 'grapes', 'orange', 'mango'],
                   'price': ['40', '80', '30', '40', '30', '80']
                   })
    fruits  price
0   orange  40
1   mango   80
2   apple   30
3   grapes  40
4   orange  30

I want to find the unique values of each column and return back a dataframe

fruits  price
0   orange  40
1   mango   80
2   apple   30
3   grapes  NaN

I am doing the following

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df=df.apply(lambda col: col.unique())
df=pd.DataFrame(df).transpose() 

which returns the following that is not what I want

            fruits                      price
0   [orange, mango, apple, grapes]  [40, 80, 30]

Any ideas?

>Solution :

You can apply pd.Series.drop_duplicates

out = df.apply(pd.Series.drop_duplicates)
   fruits price
0  orange    40
1   mango    80
2   apple    30
3  grapes   NaN
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading