Skip to main content
Version: Python

How to write a Python function to use in a query

This guide will show you how to write a Python function that can be used in the Deephaven Query Language.

By following each code step, you will add a new column to a table, which is the sum of two other columns.

In this example, a custom, user-defined function is used inside a query string to compute new column values using update.

In Python, you need to import all the tools your query will require. In this example, we are going to make a new table with integer columns by using new_table and int_col.

from deephaven import new_table
from deephaven.column import int_col

numbers = new_table([
int_col("X", [2, 4, 6]),
int_col("Y", [8, 10, 12])
])

In Python, a function is defined using the def keyword. Information can be passed into functions as arguments. Arguments are comma-separated parameters specified after the function name, inside the parentheses. Values returned by the function are specified using the return keyword.

Below we define a function called f, which has two arguments (a and b). When f is called, it returns the value a + b. For example, f(1,2) returns 3.

def f(a, b):
return a + b

We now call the function inside the query string and assign the results to a new column, Sum. Here, f is called using values in the X and Y columns.

result_numbers = numbers.update(formulas=["Sum = f(X, Y)"])
note

The result of f(X, Y) needs to be cast to an integer; otherwise, the resulting Sum column type will be Object instead of int.

The complete code block is shown below. We define a function f and use it to create a new table. The new table contains the X and Y columns from numbers, plus a new Sum column, which is the summation of columns X and Y.

from deephaven import new_table
from deephaven.column import int_col

numbers = new_table([
int_col("X", [2, 4, 6]),
int_col("Y", [8, 10, 12])
])

def f(a, b):
return a + b

result_numbers = numbers.update(formulas=["Sum = f(X, Y)"])

Once a Python function is created, it can be reused. For example, f can be used, without redefinition, to add columns from a new words table. Here, we make this table with string columns using new_table and string_col.

from deephaven.column import string_col

words = new_table([
string_col("Welcome", ["Hello ", "Hola ", "Bonjour "]),
string_col("Day", ["Monday", "Tuesday", "Wednesday"])
])

result_words = words.view(formulas=["Greeting = f(Welcome, Day)"])

Now you are ready to use your own Python functions in Deephaven!