Skip to content

pandas/merge-asof-unsorted

Rule merge-asof-unsorted
Pack pandas
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

merge_asof raises ValueError unless both frames are sorted by the key, and nothing here sorts them. Sort both frames by the key before the call.

matched = pd.merge_asof(trades, quotes, on="time")
matched = pd.merge_asof(trades.sort_values("time"), quotes.sort_values("time"), on="time")

The rule reports pd.merge_asof(...) in a function that has no sort_values and no sort_index, and at module level in a module that has none. An unsorted left frame raised ValueError "left keys must be sorted", and an unsorted right frame raised "right keys must be sorted". The rule also reports a frame that another function sorts, by mistake.

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes pd.merge_asof(left.sort_values("t"), right.sort_values("t"), on="t") when both frames are passed by position and the key by on=. The sort reorders the rows of the result. A frame passed by keyword, left_on and right_on, and the indexes have no fix.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

merge_asof raises ValueError "left keys must be sorted" unless both frames are sorted by the key, and nothing here sorts them. Write $PD.merge_asof($L.sort_values($K), $R.sort_values($K), $$$A).

Browse the other rules of the pandas pack.