Q:

Finding closest item in df2 for every item in df1

If df looks like
    row col     value
0     7   G        96
1     3   C        43
2     7   H        44
3     7   J        97
4     8   I        90
...

and q is
    row col    value
0     2   C      foo
1     8   F    bravo
2     9   F  charlie
3     2   D      bar
4     2   E      qux
...

The below code serves the purpose but is too slow.  How can I optimize this to run faster ?  It takes ~ 45 seconds when len(df) = 25000.  I need to solve for when len(df) >= 1e6. 
def foo(a):
    try:
        fxlter = q.loc[(q.row == a.row) & (q.col < a.col)]
        return q.loc[fxlter.col.idxmax()].value
    except ValueError:
        return None

df['foo'] = df.nodes.apply(foo)

(The purpose is to match the column name and row name to the value in a generic way by finding the closest row label in q for every item in df)

Desired output:
    row col  value      foo
0     7   G     96    alpha
1     3   C     43      foo
2     7   H     44    alpha
3     7   J     97    alpha
4     8   I     90    bravo
5     3   E     58      foo
6     8   H     95    bravo
7     7   I     49    alpha
8     3   D     22      foo
9     8   J     55    bravo

A:

You can use merge_asof:
df2 = pd.merge_asof(df.sort_values('col'), 
                    q.sort_values('col'), 
                    on='col', 
                    by='row', 
                    allow_exact_matches=False)

