ajsp
ajsp

Reputation: 2670

Compare two pandas columns and return index of first that matches element of second

Say we have 2 separate dataframes, with an integer index.

df1
                    dta  
0  2016-11-09 01:02:00
1  2016-11-09 01:04:00
2  2016-11-09 01:06:00

df2
                    dtb    
0  2016-11-09 01:04:00
1  2016-11-09 01:04:00
2  2016-11-09 01:04:00
3  2016-11-09 01:06:00

I am trying to get a relatively quick way of returning a list of index values from df1, where all dtb from df2 are equal to dta in df1. Of course we don't have to use dates here, I just happen to be working with them at the moment.

So in the above case our result list would be [1,1,1,2].

Thanks.

Upvotes: 1

Views: 488

Answers (2)

Andy L.
Andy L.

Reputation: 25239

df1.dta is unique, so it is simple using get_indexer

ix = df1.set_index('dta').index
ix.get_indexer(df2.dtb)

Out[1219]: array([1, 1, 1, 2], dtype=int32)

Upvotes: 2

godot
godot

Reputation: 1570

You can use pandas'Index and get_loc:

df2.apply(lambda row: pd.Index(df1.dta).get_loc(row.dtb), axis=1)

Upvotes: 0

Related Questions