Home > Mobile >  How to find index of unique elements in Pandas DataFrame?
How to find index of unique elements in Pandas DataFrame?

Time:08-19

Consider

df1 = pd.DataFrame("Name":["Adam","Joseph","James","James","Kevin","Kevin","Kevin","Peter","Peter"])

I want to get the index of the unique values in the dataframe.

When I do df1["Name"].unique() I get the output as

['Adam','Joseph','James','Kevin','Peter']

But I want to get the location of the first occurrence of each value

[0,1,2,4,7]

CodePudding user response:

I would suggest to use numpy.unique with the return_index as True.

np.unique(df1, return_index=True)
Out[13]: 
(array(['Adam', 'James', 'Joseph', 'Kevin', 'Peter'], dtype=object),
 array([0, 2, 1, 4, 7], dtype=int64))

CodePudding user response:

numpy answer is great but here is one workaround :

out = df1.reset_index().groupby(['Name'])['index'].min().to_list()

output:

[0, 1, 2, 4, 7]

CodePudding user response:

Check Below code using RANK

df1['rank'] = df1.groupby(['Name'])['Name'].rank(method='first')
df1[df1['rank'] == 1].index

Int64Index([0, 1, 2, 4, 7], dtype='int64')

CodePudding user response:

First match = first location

In[49]: import pandas as pd
   ...: df1 = pd.DataFrame({"Name":["Adam","Joseph","James","James","Kevin","Kevin","Kevin","Peter","Peter"]})
   ...: print ([df1.loc[df1['Name']==i].index[0] for i in df1['Name'].unique()])
   ...: 
[0, 1, 2, 4, 7]
  • Related