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

Community
  • 1
  • 1
Gregory Kuhn
  • 1,627
  • 2
  • 22
  • 34

2 Answers2

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
0

You can use

>>> set.union(*(set(df.index[(df.one == i) & (df.two == j)]) for i, j in c))
{0, 1}
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185