Rob Rob - 28 days ago 18
Python Question

doing joins in filter criteria in pandas

If I have two dataframes like:

df1:
| a | b |
0 | 0 | 0 |
1 | 0 | 1 |
2 | 1 | 1 |


df2:
| c | d |
0 | 0 | 1 |
1 | 1 | 1 |
2 | 2 | 1 |


how could I select rows from
df2
where
df1[df2['c']]['b'] != 0
. So in other words, rows from df2 where it's value in
column c
is the index used to check the value in
df1 column b
is not equal to 0.

So one other way to look at it. I select all the columns from
df2
where
column c
is a foreign key to
df1
, and I don't want their value in
column b
to be equal to 0.

Answer

I think this should do the trick. Let me know if you need something else.

df1['index1'] = df1.index
df = pandas.merge(df1, df2, how='left', left_on=['index1'], right_on=['c'])
df = df[df.b != 0]
Comments