1

I have a pandas dataframe:

df = pd.DataFrame({'one' : [1, 2, 3, 4] ,'two' : [5, 6, 7, 8]})
   one  two
0    1    5
1    2    6
2    3    7
3    4    8

Column "one" and column "two" together comprise (x,y) coordinates

Lets say I have a list of coordinates: c = [(1,5), (2,6), (20,5)]

Is there an elegant way of obtaining the rows in df with matching coordinates? In this case, given c, the matching rows would be 0 and 1

Related question: Using pandas to select rows using two different columns from dataframe?

And: Selecting rows from pandas DataFrame using two columns

2 Answers 2

1

This approaching using pd.merge should perform better than the iterative solutions.

import pandas as pd

df = pd.DataFrame({"one" : [1, 2, 3, 4] ,"two" : [5, 6, 7, 8]})
c = [(1, 5), (2, 6), (20, 5)]
df2 = pd.DataFrame(c, columns=["one", "two"])

pd.merge(df, df2, on=["one", "two"], how="inner")
   one  two
0    1    5
1    2    6
Sign up to request clarification or add additional context in comments.

Comments

0

You can use

>>> set.union(*(set(df.index[(df.one == i) & (df.two == j)]) for i, j in c))
{0, 1}

1 Comment

This looks to be horribly slow, I wish it wasn't marked as the correct answer. See the merge answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.