Zum Inhalt springen

Lektion 8 · Cleaning and Transforming

Expressions and Calculated Columns in KNIME

Create columns with the KNIME Expression node, reference columns and rows, write if logic and missing-value checks, and compare Math Formula and Rule Engine.

Much of data work is making new columns from old ones: a total from quantity and price, a size label from an amount, or a clean code from messy text. KNIME offers several nodes for this. This lesson focuses on the Expression node and shows where older nodes still appear.

Three expression nodes

Node Result
Expression New or replaced columns
Expression Row Filter Keeps rows where the expression is true
Variable Expression New flow variables

The expression editor includes a catalog of functions with descriptions. Use it to find names rather than guessing.

Referring to data

The syntax is small and consistent:

TEXT
$["unit price"]        column with a space in its name
$quantity              short form for a simple name
$[ROW_NUMBER]          current row number, starting at 1
$["amount", -1]        value one row above
$$["tax_rate"]         a flow variable

Column names are case-sensitive. The offset in $["amount", -1] must be a fixed number. If it points outside the table, the result is missing.

Basic calculations and logic

A revenue column:

TEXT
$["quantity"] * $["unit price"]

A label with if:

TEXT
if($["quantity"] * $["unit price"] >= 100, "large", "small")

Logical operators are and, or, and not. For equality you can write = or ==, and for inequality != or <>. Compared values must be of compatible types; integers and decimals can be compared with each other. You can also join text with + when one side is text.

Lines starting with # are comments. Use them to explain business rules, such as why 100 is the threshold.

Missing values

The literal MISSING must be written in capitals. Comparing a value with MISSING does not behave like comparing two ordinary values: according to the Expressions guide, comparisons with MISSING return false (except <= and >= when both sides are missing). So do not rely on = MISSING to find gaps, and test what your if does with a missing price, because a false comparison sends the row to the other branch. To supply a fallback value, current versions offer the ?? operator, as in $["discount"] ?? 0; older versions may differ. Also remember that arithmetic involving a missing value usually yields a missing result.

Python Stand-in: calculated columns with a missing value

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The stand-in keeps the unknown result unknown instead of calling it "small". Deciding that is a business choice: make it on purpose.

Whole-column values

Aggregation functions use an uppercase COLUMN_ prefix and take the column name as a string. For example, to compare each row with the column average:

TEXT
$["amount"] - COLUMN_AVERAGE("amount")

For group-level results, use grouping nodes, covered in grouping and pivoting.

Previous rows

Offsets make running comparisons easy, such as the change from yesterday:

TEXT
$["sales"] - $["sales", -1]

The first row has no previous row, so its result is missing. This only makes sense if the table is sorted in the right order. Sort first.

SQL Stand-in: change from the previous row

Press Run (or Ctrl + Enter) to see the result here.

SQL's LAG with an ORDER BY plays the role of sorting followed by an offset of -1.

Older and specialized nodes

You will meet other nodes in existing workflows and tutorials:

  • Math Formula evaluates a numeric expression per row. It writes columns with syntax like $price$ * 1.2.
  • String Manipulation transforms text with functions such as upper-casing or trimming.
  • Rule Engine applies an ordered list of rules, where the first matching rule wins:
TEXT
$amount$ >= 500 => "gold"
$amount$ >= 100 => "silver"
TRUE => "standard"

KNIME's String Manipulation node page describes it as superseded by the Expression node, so prefer Expression for new work. Their syntax differs from the Expression node, so do not mix them. Check the node description for the correct form in your version.

In ordered rules, put the most specific condition first. If >= 100 came before >= 500, no row could ever become gold. Test boundaries such as exactly 100 and exactly 500.

Replace or append

When you create a column, choose whether to add a new one or overwrite an existing one. Appending is safer while you develop, because the original values stay visible for comparison. Overwriting keeps tables small, but if the formula is wrong you must go back a step to see the source value. A good compromise is to append, verify, and remove the old column later with a column filter.

Types in expressions

Every expression result has a type. Dividing numbers, combining text with numbers, or mixing a missing value into a calculation can give a result you did not expect. Check the type of the new column in the node monitor, and check a division where the answer should not be a whole number. If a number arrived as text, convert it first rather than hoping the expression will cope.

Also guard against division by zero. A rate such as returned items divided by sold items needs a rule for rows with no sales. Decide whether the answer is missing, zero, or something else, and write that rule in the expression with an if, plus a comment explaining it.

Keeping expressions readable

A single expression with five nested conditions is hard to review. Split it into steps: first create a column for the revenue, then a column for the size band that uses it. Intermediate columns make errors visible. Use the comment syntax to record where a rule came from, such as the date it was agreed. When the same rule appears in several workflows, move it into a shared component so it only changes in one place.

Practice task

Using a small order table, create revenue, a size band with three levels, and the difference from the column average. Predict all values for three rows by hand, including one row with a missing price. Compare your predictions with the output and explain any difference.

When not to use an expression

An expression is the right tool for a rule that applies to each row. It is the wrong tool when the rule is really a list, such as hundreds of product codes and their categories. Put such lists in a reference table and join or look them up, so that someone can update the list without editing any formula. Likewise, if a dedicated node already does the job, such as converting text to a date, the dedicated node usually makes your intention clearer to the next reader.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. How do you reference a column named unit price in the Expression node?

    Square brackets with quotes handle names containing spaces.
  2. 2. What does $["amount", -1] refer to?

    A negative offset reads an earlier row.
  3. 3. In an ordered rule list, which rule should come first?

    The first matching rule wins, so narrow conditions must come before broad ones.

Summary

  • Expression creates columns; related nodes filter rows or set variables.
  • Use $["col"], $[ROW_NUMBER], row offsets, and $$["var"].
  • Think carefully about missing values.
  • Sort before using offsets.
  • Math Formula, String Manipulation, and Rule Engine have their own syntax.

Next: Missing Values, Duplicates, and Data Types

Dein Fortschritt wird in diesem Browser gespeichert. Kein Konto nötig.