Zum Inhalt springen

Lektion 21 · Scripting, Sharing and Practices

Python Scripting in KNIME

Use the KNIME Python Script node to read input tables, transform them with pandas, and write outputs, and decide when to choose SQL or native nodes instead.

Most tasks in KNIME need no code. Sometimes, though, you want a special calculation, a Python library, or a transformation that would take many nodes. KNIME's Python Script node runs your own Python inside a workflow. This lesson shows the interface and how to use it responsibly.

When to script

Choose the simplest tool that works:

Pick the simplest tool

Native nodes Readable and visual
Expression Row calculations
SQL Work in the database
Python Special logic or libraries
1 / 2

Native nodes are easier for others to read and check. Reach for Python when it clearly adds value. If you are new to Python, start with the Python tutorial.

The input and output API

The Python integration is an extension, which you install as described in installing KNIME. The script exchanges tables with KNIME through the knime.scripting.io module. A typical script looks like this (read-only; it runs only inside KNIME):

Python
import knime.scripting.io as knio

df = knio.input_tables[0].to_pandas()

df["revenue"] = df["quantity"] * df["unit_price"]

knio.output_tables[0] = knio.Table.from_pandas(df)
  • knio.input_tables[0] is the first input port. Numbering starts at zero, from the top port down.
  • to_pandas() converts a table to a pandas DataFrame.
  • knio.Table.from_pandas(df) converts back, and you assign it to an output port.
  • Assign something to every output port the node has.

KNIME also offers a batch approach for tables too large for memory, using the input table's batches() method together with a batch output table. See the official Python guide for details.

Test the logic outside KNIME

Keep your transformation in a function. That makes it easy to test with a few rows before wiring it into the script node. The stand-in below uses plain lists and dictionaries instead of pandas, but the structure is the same: input rows in, output rows out.

Python Stand-in: a testable transformation without pandas

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.

In pandas, missing values have their own rules, and column types may change during conversion. Check the output types in the node monitor after running the node.

Python environments

Python needs an environment with the right packages. KNIME can provide a bundled environment, and it offers other ways to define your own, including approaches based on Pixi or Conda. The details change over time, so follow the current Python integration guide. Whatever you choose:

  • List the packages and versions your script needs.
  • Check that colleagues and any server that runs the workflow have the same environment.
  • Add as few packages as you can.

SQL scripting

If the data is already in a database, a SQL query can be clearer and faster than pulling everything into Python. See databases. The query below is a typical case where SQL wins:

SQL Stand-in: a summary that belongs in SQL

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

Other integrations

KNIME also has extensions for the R language and others. The KNIME AI Extension adds nodes for large language models, such as an LLM Prompter, and lets you connect hosted providers or run local models through tools such as Ollama or GPT4All. Before sending rows to a hosted model, confirm that you may share that data, and check model output, because it can be wrong. For background, see large language models.

A script node runs real code with your permissions. Read scripts before executing a workflow someone sent you. Never place API keys or passwords in script text, and avoid downloading and running code from the internet inside a script.

Keep scripts reviewable

  • Keep them short and focused.
  • Comment on business rules, not obvious syntax.
  • Fail with a clear error if a required column is missing.
  • Do not silently change row order or drop rows.
  • Label the node with what the script does.

What changes during conversion

A KNIME table and a pandas DataFrame do not describe data in exactly the same way. Missing values, whole-number columns with gaps, text, dates, and time zones are all places to check after a round trip. When your script returns a table, look at the column types and compare them with the input. If a type changed, decide whether that matters to later nodes, and convert it back if it does. The official data type conversion guide describes how types map.

Failing loudly

A script should check its assumptions and explain failures. A message like "required column unit_price is missing" saves far more time than a long stack trace about an unknown key. Check required columns at the top, check that ranges make sense, and avoid broad exception handling that swallows errors. If you catch an error to add context, raise it again. This fragment runs only inside KNIME, after df has been created:

Python
required = {"quantity", "unit_price"}
missing = required - set(df.columns)
if missing:
    raise ValueError(f"Missing columns: {sorted(missing)}")

Large data

Converting a very large table to pandas loads it into memory. Before you do that, drop unused columns and rows with native nodes. If it is still too big, consider batch processing as described in the Python guide, or do the work in the database instead. Measure before and after so that you know the change helped.

Practice task

Write a function that adds a discounted price column, with rules for missing prices and negative quantities. Test it with at least four rows outside KNIME, then adapt it for the script node and compare the results.

Randomness and external effects

Scripts can behave differently on each run if they use random numbers, the current time, or external services. Fix random seeds, pass the reporting date in as a value instead of asking the computer for today, and keep network calls out of transformation scripts where you can. A script that only turns an input table into an output table is the easiest to test and to rerun. If a script must write files or call a service, give it a separate, clearly labeled node.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Which expression gets the first input table as a DataFrame in the Python Script node?

    Input tables are numbered from zero.
  2. 2. How do you send a DataFrame back to the first output port?

    Convert it to a KNIME table and assign it to the output slot.
  3. 3. When is Python the better choice?

    Choose the simplest tool that works.

Summary

  • The Python Script node reads inputs and writes outputs through knime.scripting.io.
  • Test logic with small inputs and handle missing values.
  • Record your Python environment so others can run the workflow.
  • Use SQL for work that belongs in the database.
  • Read scripts before running them and protect data and credentials.

Next: Sharing and Deploying Workflows

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