Filter and sort
Keep the rows you want
Section titled “Keep the rows you want”filter(condition) keeps the rows where the condition is true and drops the rest:
filter(prop("status") != "CANCELLED")filter(prop("amount") > 0 and prop("ccy") == "EUR")filter(not(empty(prop("ISIN"))))The condition must be a boolean; a one-argument filter with any other value is a type error. A filter over an empty number fails the run, so test for empty values first when a column can be blank: filter(not(empty(prop("amount"))) and prop("amount") > 0).
Drop rows where something holds
Section titled “Drop rows where something holds”dropRow() leaves the current row out of the output. Inside if, it drops the rows where the condition is true, which is the opposite reading of filter:
if(prop("expired") == 1, dropRow())That is the same row set as filter(prop("expired") != 1). Choose whichever reads more naturally for the rule you are writing. A bare dropRow() on its own line drops every row.
dropRow combines with other statements in do(…), which filter cannot: raise an exception and drop the row in one step. See Validate data.
sortBy(key, …) sorts all rows by one or more keys. The first key is primary, and a key sorts ascending unless you wrap it in desc(…):
sortBy(prop("desk"), desc(prop("notional")))- Stable: rows with equal keys keep the order they arrived in.
- Empties last: empty values sort last in both directions.
- Key types: a key is a number, text, date, or boolean (
falsebeforetrue). - Computed keys: a key can be any expression, such as
sortBy(abs(prop("pnl")))orsortBy(prop("name").lower()).
desc is valid only as a sortBy argument.
Remove duplicates
Section titled “Remove duplicates”groupBy on the columns that make a row a duplicate collapses each set of duplicates into one row. Then take one value per column:
groupBy(prop("trade_id"))setProp("trade_id", prop("trade_id").first())setProp("amount", prop("amount").first())setProp("ccy", prop("ccy").first())Rows appear in the order their key was first seen. After groupBy, every column holds the list of its members’ values, so reduce each column you keep, or drop the others with keepProps. See Group and aggregate.
Keep the latest row per key
Section titled “Keep the latest row per key”Sort first, then group and take the first member, so each key keeps the row that sorted to the top:
sortBy(prop("account"), desc(prop("as_of")))groupBy(prop("account"))setProp("account", prop("account").first())setProp("as_of", prop("as_of").first())setProp("balance", prop("balance").first())Sort, number the rows, then filter on the number:
sortBy(desc(prop("notional")))setProp("rank", rowIndex() + 1)filter(prop("rank") <= 10)The editor warns that rowIndex() follows a sortBy; here that is the point, because the rank should follow the sort.
Related
Section titled “Related”- Group and aggregate
- Validate data
- Worked examples:
filter-vs-dropRow,sortBy-desc-with-empties