Get
Function to get the value of a given field from a struct.
Parameters
field:str
The name of the field that needs to be obtained from the struct. Note that this must be a literal string, not an expression.
1from fennel.expr import col
2from fennel.dtypes import struct
3
4@struct
5class MyStruct:
6 f1: int
7 f2: bool
8
9expr = col("x").struct.get("f1")
10assert expr.typeof(schema={"x": MyStruct}) == int
11
12# error to get a field that does not exist
13expr = col("x").struct.get("z")
14with pytest.raises(ValueError):
15 expr.typeof(schema={"x": MyStruct})
16
17# can be evaluated with a dataframe
18df = pd.DataFrame(
19 {
20 "x": [MyStruct(1, True), MyStruct(2, False), None],
21 }
22)
23schema = {"x": Optional[MyStruct]}
24expr = col("x").struct.get("f1")
25assert expr.eval(df, schema=schema).tolist() == [1, 2, pd.NA]Get a field from a struct
python
Returns
Expr
Returns an expression object denoting the result of the get operation.
If the corresponding field in the struct is of type T, the resulting expression
is of type T or Optional[T] depending on the struct itself being nullable.
Errors
Use of invalid types:
The struct namespace must be invoked on an expression that evaluates to struct.
Invalid field name:
Compile error is raised when trying to get a field that doesn't exist on the struct.