Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get unique values in all columns in pandas data frame

Tags:

python

pandas

I want to list out all the unique values in all columns in a Pandas dataframe and store them in another data frame. I have tried this but its appending row wise and I want it column wise. How do I do that?

raw_data = {'student_name': ['Miller', 'Miller', 'Ali', 'Miller'], 
        'test_score': [76, 75,74,76]}
      df2 = pd.DataFrame(raw_data, columns = ['student_name', 'test_score'])


      newDF = pd.DataFrame() 

      for column in df2.columns[0:]:
          dat = df2[column].drop_duplicates()
          df3 = pd.DataFrame(dat)
          newDF = newDF.append(df3)

print(newDF)


Expected Output:
student_name  test_score
Ali          74
Miller       75
             76
like image 729
Kumar AK Avatar asked Jan 15 '18 06:01

Kumar AK


1 Answers

I think you can use drop_duplicates.

If want check some column(s) and keep first rows if dupe:

newDF = df2.drop_duplicates('student_name')
print(newDF)
   student_name  test_score
0        Miller        76.0
1      Jacobson        88.0
2           Ali        84.0
3        Milner        67.0
4         Cooze        53.0
5         Jacon        96.0
6        Ryaner        64.0
7          Sone        91.0
8         Sloan        77.0
9         Piger        73.0
10        Riani        52.0

And thank you, @cᴏʟᴅsᴘᴇᴇᴅ for another solution:

df2[~df2.student_name.duplicated()]

But if want check all columns together for dupes, keep first rows:

newDF = df2.drop_duplicates()
print(newDF)
   student_name  test_score
0        Miller        76.0
1      Jacobson        88.0
2           Ali        84.0
3        Milner        67.0
4         Cooze        53.0
5         Jacon        96.0
6        Ryaner        64.0
7          Sone        91.0
8         Sloan        77.0
9         Piger        73.0
10        Riani        52.0
11          Ali         NaN

EDIT by new sample - remove duplicates and sort by both columns:

newDF = df2.drop_duplicates().sort_values(['student_name', 'test_score'])
print(newDF)
  student_name  test_score
2          Ali          74
1       Miller          75
0       Miller          76

EDIT1: If want replace dupes by first column by NaNs:

newDF = df2.drop_duplicates().sort_values(['student_name', 'test_score'])
newDF['student_name'] = newDF['student_name'].mask(newDF['student_name'].duplicated())
print(newDF)
  student_name  test_score
2          Ali          74
1       Miller          75
0          NaN          76

EDIT2: More general solution:

newDF = df2.sort_values(df2.columns.tolist())
           .reset_index(drop=True)‌
           ​.apply(lambda x: x.drop_duplicates()) 
like image 83
jezrael Avatar answered Oct 20 '22 06:10

jezrael