Everything @MaxU said is great!
I wanted to add some context to the specific problem to which it was applied.
find_match
This is a helper function that is used in the dataframe dfWeeks.apply . Two things to note:
find_match takes a single argument x . This will be one line of dfWeeks .- Each row is a
pd.Series object, and each row will be passed through this function. This is the nature of use apply . - When
apply passes this row to a helper function, the row has a name attribute, which is equal to the index value for this row in the data frame. In this case, I know that the index value is pd.Timestamp , and I will use it to compare which I need to do.
find_match links to dfDays that are not in the scope of find_match .
I did not need to use query ... I like to use query . In my opinion, this makes the code more beautiful. The following function provided by OP could have been written differently.
def find_match(x): """Original""" match = dfDays.query('index > @x.name & price >= @x.target') if not match.empty: return match.index[0] dfWeeks.assign(target_hit=dfWeeks.apply(find_match, 1))
find_match_alt
Or we could do this, which might help explain what the query string does above.
def find_match_alt(x): """Alternative to OP's""" date_is_afterwards = dfDays.index > x.name price_target_is_met = dfDays.price >= x.target both_are_true = price_target_is_met & date_is_afterwards if (both_are_true).any(): return dfDays[both_are_true].index[0] dfWeeks.assign(target_hit=dfWeeks.apply(find_match_alt, 1))
A comparison of these two functions should give a good perspective.
source share