Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

python 3.x - Get first occurrence indices of elements in DataFrame

I have a DataFrame, df, with a datetimeindex that looks like this:

                Cluster
Date        
2021-01-28 16:39:00  1
2021-01-28 16:40:00  1
2021-01-28 16:41:00  0
2021-01-28 16:42:00  2
2021-01-28 16:43:00  1

How can I get the first occurrence indices of all Cluster elements and get an output like this:

Output: [0, 2 , 3]
question from:https://stackoverflow.com/questions/65948110/get-first-occurrence-indices-of-elements-in-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use drop_duplicates:

df.drop_duplicates('Cluster').index

Output:

Index(['2021-01-28 16:39:00', '2021-01-28 16:41:00', '2021-01-28 16:42:00'], dtype='object', name='Date')

Or if you want the row number, reset index:

df.reset_index().drop_duplicates('Cluster').index

Output:

Int64Index([0, 2, 3], dtype='int64')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...