Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of the first unique elements in Pandas DataFrame?

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]

1 Answers

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]
like image 122
eshirvana Avatar answered Oct 27 '25 00:10

eshirvana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!