CiaranWelsh
CiaranWelsh

Reputation: 7681

Getting elements from a Pandas DataFrame based on elements from another

If I have two pandas DataFrames:

y_given_x=

     y|x       probability
0    3  0.11649033348126
1    4  0.02749279374044
2    5  0.02741036003810
3    6  0.34035636232767
4    7  0.16491358255074

and

y=

     y_value       probability
0        0  0.07185269131381
1        1  0.08588676002891
2        2  0.08098779633814
3        3  0.10091839626284
4        4  0.13794741280748
5        5  0.00755474774703
6        6  0.09515832452838
7        7  0.16606587544047
8        8  0.09969027799237
9        9  0.15393771754059

How can I get all elements of y where y|x matches y_value? So the expected output in this case would be:

output=

         y_value       probability
0        3  0.10091839626284
1        4  0.13794741280748
2        5  0.00755474774703
3        6  0.09515832452838
4        7  0.16606587544047

Upvotes: 1

Views: 53

Answers (1)

jezrael
jezrael

Reputation: 862511

I think you can use merge:

print (pd.merge(y,
                y_given_x,
                left_on='y_value',
                right_on='y|x',
                suffixes=('','_'))[['y_value','probability']])

   y_value  probability
0        3     0.100918
1        4     0.137947
2        5     0.007555
3        6     0.095158
4        7     0.166066

Upvotes: 1

Related Questions