atomsmasher atomsmasher - 6 months ago 11
Python Question

Getting the index of pandas dataframe for matching row values

I have to dataframes in pandas ,

A
and
B
:

A:

A = pd.DataFrame({0:[1.24, 8.75, 4.32]})

0 1.24
1 8.75
2 4.32


where the
0 1 2 3 4 5
is the index of the dataframe

and another dataframe with strings as index:

B = pd.DataFrame({0:[9.43, 1.24, 9.09, 4.32, 8.85]}, index=['p_32','p_21','p_01','p_05','p_76'])

'p_32' 9.43
'p_21' 1.24
'p_01' 9.09
'p_05' 4.32
'p_76' 8.75


All of the numbers in the first column of
A
are contained in
B
but not the other way around. I want to get the index strings of
B
whos row number matches
A
, while retaining the order that in
A


So I would need:

'p_21'
'p_76'
'p_05'

Answer

you can use isin() function for that:

In [141]: B[B[0].isin(A[0])].index
Out[141]: Index(['p_21', 'p_05', 'p_76'], dtype='object')

In [142]: B[B[0].isin(A[0])]
Out[142]:
         0
p_21  1.24
p_05  4.32
p_76  8.75

data:

In [139]: A
Out[139]:
      0
0  1.24
1  8.75
2  4.32

In [140]: B
Out[140]:
         0
p_32  9.43
p_21  1.24
p_01  9.09
p_05  4.32
p_76  8.75