Pandas – Lookup values from one dataframe in multiple columns of another dataframe

dataframe, pandas

I currently have a dataframe (df1) with one columns being a list of numbers. I want to look up those numbers in another dataframe (df2) that has two integer columns and see if the number from df1 falls in between the range of those two columns and get the data from the matching row. Below is my current approach, is there a better way of doing this?

for index, row in df1.iterrows():    print df2[(df2['start'] <=  row['num']) & (df2['end'] >= row['num'])]['data'].iloc[0]

Here is what the head of df1 looks like:

           num0  12169425351  12204321292  1501931542

head of df2:

                organization_name       start         end  0                Service 2000 Srl  1478947232  1478947239  1  Autolinee F Lli Bucci Urbino P  1478947240  1478947247  2         S.M.S. DISTRIBUTION SRL  1478947248  1478947255  3                    ALTOPACK SRL  1478947256  1478947263  4                   COPYWORLD SRL  1478947264  1478947271  

Best Solution

Basic use of .loc and boolean array logic :

# parentheses are mandatory hereresult = df2.loc[(df1.num < df2.end) & (df1.num > df2.start), "organization_name"]

Test with Minimal Wirking Example :

df1 = pd.DataFrame(np.random.randint(0, 10, 5))df2 = pd.DataFrame({        "orgname": [str(i) for i in range(5)],         "start": np.random.randint(-5, 5, 5),         "end": np.random.randint(5, 15, 5)    })[["orgname", "start", "end"]]df2.loc[(df1[0] < df2.end) & (df1[0] > df2.start), "orgname"]