Selecting DataFrame rows based on comparison with other DataFrame

Viewed 125

I Have two DataFrames like this:

df_A = pd.DataFrame({
    'id': [2],
    'number': [20]
})

df_B = pd.DataFrame({
    'words': ['Hello', 'world', 'aloha'],
    'id': [3, 4, 1],
    'number': [17, 18, 10]
})

I want to select only the rows from df_B for which the following criteria is met:

(df_B.id >= df_A.id ) & (df_B.number <= df_A.number)

For our case the result would look like this:

words            id             number
Hello            3              17
World            4              18

This seems to work when I compare against values of df_A as scalars but I want a better solution by comparing the dataframes. Would appreciate some help.

1 Answers

You need cross join for one DataFrame, so possible compare and filter:

df = df1.assign(a=1).merge(df2.assign(a=1), on='a')
df = df[(df.id_x >= df.id_y ) & (df.number_x <= df.number_y)]
Related