fenic.api.dataframe
DataFrame API for Fenic - provides DataFrame and grouped data operations.
Classes:
-
DataFrame
–A data collection organized into named columns.
-
GroupedData
–Methods for aggregations on a grouped DataFrame.
-
SemanticExtensions
–A namespace for semantic dataframe operators.
DataFrame
A data collection organized into named columns.
The DataFrame class represents a lazily evaluated computation on data. Operations on DataFrame build up a logical query plan that is only executed when an action like show(), to_polars(), to_pandas(), to_arrow(), to_pydict(), to_pylist(), or count() is called.
The DataFrame supports method chaining for building complex transformations.
Create and transform a DataFrame
# Create a DataFrame from a dictionary
df = session.create_dataframe({"id": [1, 2, 3], "value": ["a", "b", "c"]})
# Chain transformations
result = df.filter(col("id") > 1).select("id", "value")
# Show results
result.show()
# Output:
# +---+-----+
# | id|value|
# +---+-----+
# | 2| b|
# | 3| c|
# +---+-----+
Methods:
-
agg
–Aggregate on the entire DataFrame without groups.
-
cache
–Alias for persist(). Mark DataFrame for caching after first computation.
-
collect
–Execute the DataFrame computation and return the result as a QueryResult.
-
count
–Count the number of rows in the DataFrame.
-
drop
–Remove one or more columns from this DataFrame.
-
drop_duplicates
–Return a DataFrame with duplicate rows removed.
-
explain
–Display the logical plan of the DataFrame.
-
explode
–Create a new row for each element in an array column.
-
filter
–Filters rows using the given condition.
-
group_by
–Groups the DataFrame using the specified columns.
-
join
–Joins this DataFrame with another DataFrame.
-
limit
–Limits the number of rows to the specified number.
-
lineage
–Create a Lineage object to trace data through transformations.
-
order_by
–Sort the DataFrame by the specified columns. Alias for sort().
-
persist
–Mark this DataFrame to be persisted after first computation.
-
select
–Projects a set of Column expressions or column names.
-
show
–Display the DataFrame content in a tabular form.
-
sort
–Sort the DataFrame by the specified columns.
-
to_arrow
–Execute the DataFrame computation and return an Apache Arrow Table.
-
to_pandas
–Execute the DataFrame computation and return a Pandas DataFrame.
-
to_polars
–Execute the DataFrame computation and return the result as a Polars DataFrame.
-
to_pydict
–Execute the DataFrame computation and return a dictionary of column arrays.
-
to_pylist
–Execute the DataFrame computation and return a list of row dictionaries.
-
union
–Return a new DataFrame containing the union of rows in this and another DataFrame.
-
unnest
–Unnest the specified struct columns into separate columns.
-
where
–Filters rows using the given condition (alias for filter()).
-
with_column
–Add a new column or replace an existing column.
-
with_column_renamed
–Rename a column. No-op if the column does not exist.
Attributes:
-
columns
(List[str]
) –Get list of column names.
-
schema
(Schema
) –Get the schema of this DataFrame.
-
semantic
(SemanticExtensions
) –Interface for semantic operations on the DataFrame.
-
write
(DataFrameWriter
) –Interface for saving the content of the DataFrame.
columns
property
columns: List[str]
Get list of column names.
Returns:
-
List[str]
–List[str]: List of all column names in the DataFrame
Examples:
>>> df.columns
['name', 'age', 'city']
schema
property
schema: Schema
Get the schema of this DataFrame.
Returns:
-
Schema
(Schema
) –Schema containing field names and data types
Examples:
>>> df.schema
Schema([
ColumnField('name', StringType),
ColumnField('age', IntegerType)
])
semantic
property
semantic: SemanticExtensions
Interface for semantic operations on the DataFrame.
write
property
write: DataFrameWriter
Interface for saving the content of the DataFrame.
Returns:
-
DataFrameWriter
(DataFrameWriter
) –Writer interface to write DataFrame.
agg
agg(*exprs: Union[Column, Dict[str, str]]) -> DataFrame
Aggregate on the entire DataFrame without groups.
This is equivalent to group_by() without any grouping columns.
Parameters:
-
*exprs
(Union[Column, Dict[str, str]]
, default:()
) –Aggregation expressions or dictionary of aggregations.
Returns:
-
DataFrame
(DataFrame
) –Aggregation results.
Multiple aggregations
# Create sample DataFrame
df = session.create_dataframe({
"salary": [80000, 70000, 90000, 75000, 85000],
"age": [25, 30, 35, 28, 32]
})
# Multiple aggregations
df.agg(
count().alias("total_rows"),
avg(col("salary")).alias("avg_salary")
).show()
# Output:
# +----------+-----------+
# |total_rows|avg_salary|
# +----------+-----------+
# | 5| 80000.0|
# +----------+-----------+
Dictionary style
# Dictionary style
df.agg({col("salary"): "avg", col("age"): "max"}).show()
# Output:
# +-----------+--------+
# |avg(salary)|max(age)|
# +-----------+--------+
# | 80000.0| 35|
# +-----------+--------+
Source code in src/fenic/api/dataframe/dataframe.py
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 |
|
cache
cache() -> DataFrame
Alias for persist(). Mark DataFrame for caching after first computation.
Returns:
-
DataFrame
(DataFrame
) –Same DataFrame, but marked for caching
See Also
persist(): Full documentation of caching behavior
Source code in src/fenic/api/dataframe/dataframe.py
405 406 407 408 409 410 411 412 413 414 |
|
collect
collect(data_type: DataLikeType = 'polars') -> QueryResult
Execute the DataFrame computation and return the result as a QueryResult.
This is an action that triggers computation of the DataFrame query plan. All transformations and operations are executed, and the results are materialized into a QueryResult, which contains both the result data and the query metrics.
Parameters:
-
data_type
(DataLikeType
, default:'polars'
) –The type of data to return
Returns:
-
QueryResult
(QueryResult
) –A QueryResult with materialized data and query metrics
Source code in src/fenic/api/dataframe/dataframe.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
|
count
count() -> int
Count the number of rows in the DataFrame.
This is an action that triggers computation of the DataFrame. The output is an integer representing the number of rows.
Returns:
-
int
(int
) –The number of rows in the DataFrame
Source code in src/fenic/api/dataframe/dataframe.py
339 340 341 342 343 344 345 346 347 348 |
|
drop
drop(*col_names: str) -> DataFrame
Remove one or more columns from this DataFrame.
Parameters:
-
*col_names
(str
, default:()
) –Names of columns to drop.
Returns:
-
DataFrame
(DataFrame
) –New DataFrame without specified columns.
Raises:
-
ValueError
–If any specified column doesn't exist in the DataFrame.
-
ValueError
–If dropping the columns would result in an empty DataFrame.
Drop single column
# Create sample DataFrame
df = session.create_dataframe({
"id": [1, 2, 3],
"name": ["Alice", "Bob", "Charlie"],
"age": [25, 30, 35]
})
# Drop single column
df.drop("age").show()
# Output:
# +---+-------+
# | id| name|
# +---+-------+
# | 1| Alice|
# | 2| Bob|
# | 3|Charlie|
# +---+-------+
Drop multiple columns
# Drop multiple columns
df.drop(col("id"), "age").show()
# Output:
# +-------+
# | name|
# +-------+
# | Alice|
# | Bob|
# |Charlie|
# +-------+
Error when dropping non-existent column
# This will raise a ValueError
df.drop("non_existent_column")
# ValueError: Column 'non_existent_column' not found in DataFrame
Source code in src/fenic/api/dataframe/dataframe.py
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 |
|
drop_duplicates
drop_duplicates(subset: Optional[List[str]] = None) -> DataFrame
Return a DataFrame with duplicate rows removed.
Parameters:
-
subset
(Optional[List[str]]
, default:None
) –Column names to consider when identifying duplicates. If not provided, all columns are considered.
Returns:
-
DataFrame
(DataFrame
) –A new DataFrame with duplicate rows removed.
Raises:
-
ValueError
–If a specified column is not present in the current DataFrame schema.
Remove duplicates considering specific columns
# Create sample DataFrame
df = session.create_dataframe({
"c1": [1, 2, 3, 1],
"c2": ["a", "a", "a", "a"],
"c3": ["b", "b", "b", "b"]
})
# Remove duplicates considering all columns
df.drop_duplicates([col("c1"), col("c2"), col("c3")]).show()
# Output:
# +---+---+---+
# | c1| c2| c3|
# +---+---+---+
# | 1| a| b|
# | 2| a| b|
# | 3| a| b|
# +---+---+---+
# Remove duplicates considering only c1
df.drop_duplicates([col("c1")]).show()
# Output:
# +---+---+---+
# | c1| c2| c3|
# +---+---+---+
# | 1| a| b|
# | 2| a| b|
# | 3| a| b|
# +---+---+---+
Source code in src/fenic/api/dataframe/dataframe.py
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 |
|
explain
explain() -> None
Display the logical plan of the DataFrame.
Source code in src/fenic/api/dataframe/dataframe.py
221 222 223 |
|
explode
explode(column: ColumnOrName) -> DataFrame
Create a new row for each element in an array column.
This operation is useful for flattening nested data structures. For each row in the input DataFrame that contains an array/list in the specified column, this method will: 1. Create N new rows, where N is the length of the array 2. Each new row will be identical to the original row, except the array column will contain just a single element from the original array 3. Rows with NULL values or empty arrays in the specified column are filtered out
Parameters:
-
column
(ColumnOrName
) –Name of array column to explode (as string) or Column expression.
Returns:
-
DataFrame
(DataFrame
) –New DataFrame with the array column exploded into multiple rows.
Raises:
-
TypeError
–If column argument is not a string or Column.
Explode array column
# Create sample DataFrame
df = session.create_dataframe({
"id": [1, 2, 3, 4],
"tags": [["red", "blue"], ["green"], [], None],
"name": ["Alice", "Bob", "Carol", "Dave"]
})
# Explode the tags column
df.explode("tags").show()
# Output:
# +---+-----+-----+
# | id| tags| name|
# +---+-----+-----+
# | 1| red|Alice|
# | 1| blue|Alice|
# | 2|green| Bob|
# +---+-----+-----+
Using column expression
# Explode using column expression
df.explode(col("tags")).show()
# Output:
# +---+-----+-----+
# | id| tags| name|
# +---+-----+-----+
# | 1| red|Alice|
# | 1| blue|Alice|
# | 2|green| Bob|
# +---+-----+-----+
Source code in src/fenic/api/dataframe/dataframe.py
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 |
|
filter
filter(condition: Column) -> DataFrame
Filters rows using the given condition.
Parameters:
-
condition
(Column
) –A Column expression that evaluates to a boolean
Returns:
-
DataFrame
(DataFrame
) –Filtered DataFrame
Filter with numeric comparison
# Create a DataFrame
df = session.create_dataframe({"age": [25, 30, 35], "name": ["Alice", "Bob", "Charlie"]})
# Filter with numeric comparison
df.filter(col("age") > 25).show()
# Output:
# +---+-------+
# |age| name|
# +---+-------+
# | 30| Bob|
# | 35|Charlie|
# +---+-------+
Filter with semantic predicate
# Filter with semantic predicate
df.filter((col("age") > 25) & semantic.predicate("This {feedback} mentions problems with the user interface or navigation")).show()
# Output:
# +---+-------+
# |age| name|
# +---+-------+
# | 30| Bob|
# | 35|Charlie|
# +---+-------+
Filter with multiple conditions
# Filter with multiple conditions
df.filter((col("age") > 25) & (col("age") <= 35)).show()
# Output:
# +---+-------+
# |age| name|
# +---+-------+
# | 30| Bob|
# | 35|Charlie|
# +---+-------+
Source code in src/fenic/api/dataframe/dataframe.py
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
|
group_by
group_by(*cols: ColumnOrName) -> GroupedData
Groups the DataFrame using the specified columns.
Parameters:
-
*cols
(ColumnOrName
, default:()
) –Columns to group by. Can be column names as strings or Column expressions.
Returns:
-
GroupedData
(GroupedData
) –Object for performing aggregations on the grouped data.
Group by single column
# Create sample DataFrame
df = session.create_dataframe({
"department": ["IT", "HR", "IT", "HR", "IT"],
"salary": [80000, 70000, 90000, 75000, 85000]
})
# Group by single column
df.group_by(col("department")).count().show()
# Output:
# +----------+-----+
# |department|count|
# +----------+-----+
# | IT| 3|
# | HR| 2|
# +----------+-----+
Group by multiple columns
# Group by multiple columns
df.group_by(col("department"), col("location")).agg({"salary": "avg"}).show()
# Output:
# +----------+--------+-----------+
# |department|location|avg(salary)|
# +----------+--------+-----------+
# | IT| NYC| 85000.0|
# | HR| NYC| 72500.0|
# +----------+--------+-----------+
Group by expression
# Group by expression
df.group_by(col("age").cast("int").alias("age_group")).count().show()
# Output:
# +---------+-----+
# |age_group|count|
# +---------+-----+
# | 20| 2|
# | 30| 3|
# | 40| 1|
# +---------+-----+
Source code in src/fenic/api/dataframe/dataframe.py
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 |
|
join
join(other: DataFrame, on: Union[str, List[str]], *, how: JoinType = 'inner') -> DataFrame
join(other: DataFrame, *, left_on: Union[ColumnOrName, List[ColumnOrName]], right_on: Union[ColumnOrName, List[ColumnOrName]], how: JoinType = 'inner') -> DataFrame
join(other: DataFrame, on: Optional[Union[str, List[str]]] = None, *, left_on: Optional[Union[ColumnOrName, List[ColumnOrName]]] = None, right_on: Optional[Union[ColumnOrName, List[ColumnOrName]]] = None, how: JoinType = 'inner') -> DataFrame
Joins this DataFrame with another DataFrame.
The Dataframes must have no duplicate column names between them. This API only supports equi-joins. For non-equi-joins, use session.sql().
Parameters:
-
other
(DataFrame
) –DataFrame to join with.
-
on
(Optional[Union[str, List[str]]]
, default:None
) –Join condition(s). Can be: - A column name (str) - A list of column names (List[str]) - A Column expression (e.g., col('a')) - A list of Column expressions -
None
for cross joins -
left_on
(Optional[Union[ColumnOrName, List[ColumnOrName]]]
, default:None
) –Column(s) from the left DataFrame to join on. Can be: - A column name (str) - A Column expression (e.g., col('a'), col('a') + 1) - A list of column names or expressions
-
right_on
(Optional[Union[ColumnOrName, List[ColumnOrName]]]
, default:None
) –Column(s) from the right DataFrame to join on. Can be: - A column name (str) - A Column expression (e.g., col('b'), upper(col('b'))) - A list of column names or expressions
-
how
(JoinType
, default:'inner'
) –Type of join to perform.
Returns:
-
DataFrame
–Joined DataFrame.
Raises:
-
ValidationError
–If cross join is used with an ON clause.
-
ValidationError
–If join condition is invalid.
-
ValidationError
–If both 'on' and 'left_on'/'right_on' parameters are provided.
-
ValidationError
–If only one of 'left_on' or 'right_on' is provided.
-
ValidationError
–If 'left_on' and 'right_on' have different lengths
Inner join on column name
# Create sample DataFrames
df1 = session.create_dataframe({
"id": [1, 2, 3],
"name": ["Alice", "Bob", "Charlie"]
})
df2 = session.create_dataframe({
"id": [1, 2, 4],
"age": [25, 30, 35]
})
# Join on single column
df1.join(df2, on=col("id")).show()
# Output:
# +---+-----+---+
# | id| name|age|
# +---+-----+---+
# | 1|Alice| 25|
# | 2| Bob| 30|
# +---+-----+---+
Join with expression
# Join with Column expressions
df1.join(
df2,
left_on=col("id"),
right_on=col("id"),
).show()
# Output:
# +---+-----+---+
# | id| name|age|
# +---+-----+---+
# | 1|Alice| 25|
# | 2| Bob| 30|
# +---+-----+---+
Cross join
# Cross join (cartesian product)
df1.join(df2, how="cross").show()
# Output:
# +---+-----+---+---+
# | id| name| id|age|
# +---+-----+---+---+
# | 1|Alice| 1| 25|
# | 1|Alice| 2| 30|
# | 1|Alice| 4| 35|
# | 2| Bob| 1| 25|
# | 2| Bob| 2| 30|
# | 2| Bob| 4| 35|
# | 3|Charlie| 1| 25|
# | 3|Charlie| 2| 30|
# | 3|Charlie| 4| 35|
# +---+-----+---+---+
Source code in src/fenic/api/dataframe/dataframe.py
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 |
|
limit
limit(n: int) -> DataFrame
Limits the number of rows to the specified number.
Parameters:
-
n
(int
) –Maximum number of rows to return.
Returns:
-
DataFrame
(DataFrame
) –DataFrame with at most n rows.
Raises:
-
TypeError
–If n is not an integer.
Limit rows
# Create sample DataFrame
df = session.create_dataframe({
"id": [1, 2, 3, 4, 5],
"name": ["Alice", "Bob", "Charlie", "Dave", "Eve"]
})
# Get first 3 rows
df.limit(3).show()
# Output:
# +---+-------+
# | id| name|
# +---+-------+
# | 1| Alice|
# | 2| Bob|
# | 3|Charlie|
# +---+-------+
Limit with other operations
# Limit after filtering
df.filter(col("id") > 2).limit(2).show()
# Output:
# +---+-------+
# | id| name|
# +---+-------+
# | 3|Charlie|
# | 4| Dave|
# +---+-------+
Source code in src/fenic/api/dataframe/dataframe.py
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 |
|
lineage
lineage() -> Lineage
Create a Lineage object to trace data through transformations.
The Lineage interface allows you to trace how specific rows are transformed through your DataFrame operations, both forwards and backwards through the computation graph.
Returns:
-
Lineage
(Lineage
) –Interface for querying data lineage
Example
# Create lineage query
lineage = df.lineage()
# Trace specific rows backwards through transformations
source_rows = lineage.backward(["result_uuid1", "result_uuid2"])
# Or trace forwards to see outputs
result_rows = lineage.forward(["source_uuid1"])
See Also
LineageQuery: Full documentation of lineage querying capabilities
Source code in src/fenic/api/dataframe/dataframe.py
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
|
order_by
order_by(cols: Union[ColumnOrName, List[ColumnOrName], None] = None, ascending: Optional[Union[bool, List[bool]]] = None) -> 'DataFrame'
Sort the DataFrame by the specified columns. Alias for sort().
Returns:
-
DataFrame
('DataFrame'
) –sorted Dataframe.
See Also
sort(): Full documentation of sorting behavior and parameters.
Source code in src/fenic/api/dataframe/dataframe.py
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 |
|
persist
persist() -> DataFrame
Mark this DataFrame to be persisted after first computation.
The persisted DataFrame will be cached after its first computation, avoiding recomputation in subsequent operations. This is useful for DataFrames that are reused multiple times in your workflow.
Returns:
-
DataFrame
(DataFrame
) –Same DataFrame, but marked for persistence
Example
# Cache intermediate results for reuse
filtered_df = (df
.filter(col("age") > 25)
.persist() # Cache these results
)
# Both operations will use cached results
result1 = filtered_df.group_by("department").count()
result2 = filtered_df.select("name", "salary")
Source code in src/fenic/api/dataframe/dataframe.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
|
select
select(*cols: ColumnOrName) -> DataFrame
Projects a set of Column expressions or column names.
Parameters:
-
*cols
(ColumnOrName
, default:()
) –Column expressions to select. Can be: - String column names (e.g., "id", "name") - Column objects (e.g., col("id"), col("age") + 1)
Returns:
-
DataFrame
(DataFrame
) –A new DataFrame with selected columns
Select by column names
# Create a DataFrame
df = session.create_dataframe({"name": ["Alice", "Bob"], "age": [25, 30]})
# Select by column names
df.select(col("name"), col("age")).show()
# Output:
# +-----+---+
# | name|age|
# +-----+---+
# |Alice| 25|
# | Bob| 30|
# +-----+---+
Select with expressions
# Select with expressions
df.select(col("name"), col("age") + 1).show()
# Output:
# +-----+-------+
# | name|age + 1|
# +-----+-------+
# |Alice| 26|
# | Bob| 31|
# +-----+-------+
Mix strings and expressions
# Mix strings and expressions
df.select(col("name"), col("age") * 2).show()
# Output:
# +-----+-------+
# | name|age * 2|
# +-----+-------+
# |Alice| 50|
# | Bob| 60|
# +-----+-------+
Source code in src/fenic/api/dataframe/dataframe.py
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
|
show
show(n: int = 10, explain_analyze: bool = False) -> None
Display the DataFrame content in a tabular form.
This is an action that triggers computation of the DataFrame. The output is printed to stdout in a formatted table.
Parameters:
-
n
(int
, default:10
) –Number of rows to display
-
explain_analyze
(bool
, default:False
) –Whether to print the explain analyze plan
Source code in src/fenic/api/dataframe/dataframe.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
|
sort
sort(cols: Union[ColumnOrName, List[ColumnOrName], None] = None, ascending: Optional[Union[bool, List[bool]]] = None) -> DataFrame
Sort the DataFrame by the specified columns.
Parameters:
-
cols
(Union[ColumnOrName, List[ColumnOrName], None]
, default:None
) –Columns to sort by. This can be: - A single column name (str) - A Column expression (e.g.,
col("name")
) - A list of column names or Column expressions - Column expressions may include sorting directives such asasc("col")
,desc("col")
,asc_nulls_last("col")
, etc. - If no columns are provided, the operation is a no-op. -
ascending
(Optional[Union[bool, List[bool]]]
, default:None
) –A boolean or list of booleans indicating sort order. - If
True
, sorts in ascending order; ifFalse
, descending. - If a list is provided, its length must match the number of columns. - Cannot be used if any of the columns useasc()
/desc()
expressions. - If not specified and no sort expressions are used, columns will be sorted in ascending order by default.
Returns:
-
DataFrame
(DataFrame
) –A new DataFrame sorted by the specified columns.
Raises:
-
ValueError
–- If
ascending
is provided and its length does not matchcols
- If both
ascending
and column expressions likeasc()
/desc()
are used
- If
-
TypeError
–- If
cols
is not a column name, Column, or list of column names/Columns - If
ascending
is not a boolean or list of booleans
- If
Sort in ascending order
# Create sample DataFrame
df = session.create_dataframe([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
# Sort by age in ascending order
df.sort(asc(col("age"))).show()
# Output:
# +---+-----+
# |age| name|
# +---+-----+
# | 2|Alice|
# | 5| Bob|
# +---+-----+
Sort in descending order
# Sort by age in descending order
df.sort(col("age").desc()).show()
# Output:
# +---+-----+
# |age| name|
# +---+-----+
# | 5| Bob|
# | 2|Alice|
# +---+-----+
Sort with boolean ascending parameter
# Sort by age in descending order using boolean
df.sort(col("age"), ascending=False).show()
# Output:
# +---+-----+
# |age| name|
# +---+-----+
# | 5| Bob|
# | 2|Alice|
# +---+-----+
Multiple columns with different sort orders
# Create sample DataFrame
df = session.create_dataframe([(2, "Alice"), (2, "Bob"), (5, "Bob")], schema=["age", "name"])
# Sort by age descending, then name ascending
df.sort(desc(col("age")), col("name")).show()
# Output:
# +---+-----+
# |age| name|
# +---+-----+
# | 5| Bob|
# | 2|Alice|
# | 2| Bob|
# +---+-----+
Multiple columns with list of ascending strategies
# Sort both columns in descending order
df.sort([col("age"), col("name")], ascending=[False, False]).show()
# Output:
# +---+-----+
# |age| name|
# +---+-----+
# | 5| Bob|
# | 2| Bob|
# | 2|Alice|
# +---+-----+
Source code in src/fenic/api/dataframe/dataframe.py
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 |
|
to_arrow
to_arrow() -> pa.Table
Execute the DataFrame computation and return an Apache Arrow Table.
This is an action that triggers computation of the DataFrame query plan. All transformations and operations are executed, and the results are materialized into an Apache Arrow Table with columnar memory layout optimized for analytics and zero-copy data exchange.
Returns:
-
Table
–pa.Table: An Apache Arrow Table containing the computed results
Source code in src/fenic/api/dataframe/dataframe.py
295 296 297 298 299 300 301 302 303 304 305 306 |
|
to_pandas
to_pandas() -> pd.DataFrame
Execute the DataFrame computation and return a Pandas DataFrame.
This is an action that triggers computation of the DataFrame query plan. All transformations and operations are executed, and the results are materialized into a Pandas DataFrame.
Returns:
-
DataFrame
–pd.DataFrame: A Pandas DataFrame containing the computed results with
Source code in src/fenic/api/dataframe/dataframe.py
283 284 285 286 287 288 289 290 291 292 293 |
|
to_polars
to_polars() -> pl.DataFrame
Execute the DataFrame computation and return the result as a Polars DataFrame.
This is an action that triggers computation of the DataFrame query plan. All transformations and operations are executed, and the results are materialized into a Polars DataFrame.
Returns:
-
DataFrame
–pl.DataFrame: A Polars DataFrame with materialized results
Source code in src/fenic/api/dataframe/dataframe.py
271 272 273 274 275 276 277 278 279 280 281 |
|
to_pydict
to_pydict() -> Dict[str, List[Any]]
Execute the DataFrame computation and return a dictionary of column arrays.
This is an action that triggers computation of the DataFrame query plan. All transformations and operations are executed, and the results are materialized into a Python dictionary where each column becomes a list of values.
Returns:
-
Dict[str, List[Any]]
–Dict[str, List[Any]]: A dictionary containing the computed results with: - Keys: Column names as strings - Values: Lists containing all values for each column
Source code in src/fenic/api/dataframe/dataframe.py
308 309 310 311 312 313 314 315 316 317 318 319 320 |
|
to_pylist
to_pylist() -> List[Dict[str, Any]]
Execute the DataFrame computation and return a list of row dictionaries.
This is an action that triggers computation of the DataFrame query plan. All transformations and operations are executed, and the results are materialized into a Python list where each element is a dictionary representing one row with column names as keys.
Returns:
-
List[Dict[str, Any]]
–List[Dict[str, Any]]: A list containing the computed results with: - Each element: A dictionary representing one row - Dictionary keys: Column names as strings - Dictionary values: Cell values in Python native types - List length equals number of rows in the result
Source code in src/fenic/api/dataframe/dataframe.py
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
|
union
union(other: DataFrame) -> DataFrame
Return a new DataFrame containing the union of rows in this and another DataFrame.
This is equivalent to UNION ALL in SQL. To remove duplicates, use drop_duplicates() after union().
Parameters:
-
other
(DataFrame
) –Another DataFrame with the same schema.
Returns:
-
DataFrame
(DataFrame
) –A new DataFrame containing rows from both DataFrames.
Raises:
-
ValueError
–If the DataFrames have different schemas.
-
TypeError
–If other is not a DataFrame.
Union two DataFrames
# Create two DataFrames
df1 = session.create_dataframe({
"id": [1, 2],
"value": ["a", "b"]
})
df2 = session.create_dataframe({
"id": [3, 4],
"value": ["c", "d"]
})
# Union the DataFrames
df1.union(df2).show()
# Output:
# +---+-----+
# | id|value|
# +---+-----+
# | 1| a|
# | 2| b|
# | 3| c|
# | 4| d|
# +---+-----+
Union with duplicates
# Create DataFrames with overlapping data
df1 = session.create_dataframe({
"id": [1, 2],
"value": ["a", "b"]
})
df2 = session.create_dataframe({
"id": [2, 3],
"value": ["b", "c"]
})
# Union with duplicates
df1.union(df2).show()
# Output:
# +---+-----+
# | id|value|
# +---+-----+
# | 1| a|
# | 2| b|
# | 2| b|
# | 3| c|
# +---+-----+
# Remove duplicates after union
df1.union(df2).drop_duplicates().show()
# Output:
# +---+-----+
# | id|value|
# +---+-----+
# | 1| a|
# | 2| b|
# | 3| c|
# +---+-----+
Source code in src/fenic/api/dataframe/dataframe.py
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 |
|
unnest
unnest(*col_names: str) -> DataFrame
Unnest the specified struct columns into separate columns.
This operation flattens nested struct data by expanding each field of a struct into its own top-level column.
For each specified column containing a struct: 1. Each field in the struct becomes a separate column. 2. New columns are named after the corresponding struct fields. 3. The new columns are inserted into the DataFrame in place of the original struct column. 4. The overall column order is preserved.
Parameters:
-
*col_names
(str
, default:()
) –One or more struct columns to unnest. Each can be a string (column name) or a Column expression.
Returns:
-
DataFrame
(DataFrame
) –A new DataFrame with the specified struct columns expanded.
Raises:
-
TypeError
–If any argument is not a string or Column.
-
ValueError
–If a specified column does not contain struct data.
Unnest struct column
# Create sample DataFrame
df = session.create_dataframe({
"id": [1, 2],
"tags": [{"red": 1, "blue": 2}, {"red": 3}],
"name": ["Alice", "Bob"]
})
# Unnest the tags column
df.unnest(col("tags")).show()
# Output:
# +---+---+----+-----+
# | id| red|blue| name|
# +---+---+----+-----+
# | 1| 1| 2|Alice|
# | 2| 3|null| Bob|
# +---+---+----+-----+
Unnest multiple struct columns
# Create sample DataFrame with multiple struct columns
df = session.create_dataframe({
"id": [1, 2],
"tags": [{"red": 1, "blue": 2}, {"red": 3}],
"info": [{"age": 25, "city": "NY"}, {"age": 30, "city": "LA"}],
"name": ["Alice", "Bob"]
})
# Unnest multiple struct columns
df.unnest(col("tags"), col("info")).show()
# Output:
# +---+---+----+---+----+-----+
# | id| red|blue|age|city| name|
# +---+---+----+---+----+-----+
# | 1| 1| 2| 25| NY|Alice|
# | 2| 3|null| 30| LA| Bob|
# +---+---+----+---+----+-----+
Source code in src/fenic/api/dataframe/dataframe.py
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 |
|
where
where(condition: Column) -> DataFrame
Filters rows using the given condition (alias for filter()).
Parameters:
-
condition
(Column
) –A Column expression that evaluates to a boolean
Returns:
-
DataFrame
(DataFrame
) –Filtered DataFrame
See Also
filter(): Full documentation of filtering behavior
Source code in src/fenic/api/dataframe/dataframe.py
485 486 487 488 489 490 491 492 493 494 495 496 497 |
|
with_column
with_column(col_name: str, col: Union[Any, Column]) -> DataFrame
Add a new column or replace an existing column.
Parameters:
-
col_name
(str
) –Name of the new column
-
col
(Union[Any, Column]
) –Column expression or value to assign to the column. If not a Column, it will be treated as a literal value.
Returns:
-
DataFrame
(DataFrame
) –New DataFrame with added/replaced column
Add literal column
# Create a DataFrame
df = session.create_dataframe({"name": ["Alice", "Bob"], "age": [25, 30]})
# Add literal column
df.with_column("constant", lit(1)).show()
# Output:
# +-----+---+--------+
# | name|age|constant|
# +-----+---+--------+
# |Alice| 25| 1|
# | Bob| 30| 1|
# +-----+---+--------+
Add computed column
# Add computed column
df.with_column("double_age", col("age") * 2).show()
# Output:
# +-----+---+----------+
# | name|age|double_age|
# +-----+---+----------+
# |Alice| 25| 50|
# | Bob| 30| 60|
# +-----+---+----------+
Replace existing column
# Replace existing column
df.with_column("age", col("age") + 1).show()
# Output:
# +-----+---+
# | name|age|
# +-----+---+
# |Alice| 26|
# | Bob| 31|
# +-----+---+
Add column with complex expression
# Add column with complex expression
df.with_column(
"age_category",
when(col("age") < 30, "young")
.when(col("age") < 50, "middle")
.otherwise("senior")
).show()
# Output:
# +-----+---+------------+
# | name|age|age_category|
# +-----+---+------------+
# |Alice| 25| young|
# | Bob| 30| middle|
# +-----+---+------------+
Source code in src/fenic/api/dataframe/dataframe.py
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 |
|
with_column_renamed
with_column_renamed(col_name: str, new_col_name: str) -> DataFrame
Rename a column. No-op if the column does not exist.
Parameters:
-
col_name
(str
) –Name of the column to rename.
-
new_col_name
(str
) –New name for the column.
Returns:
-
DataFrame
(DataFrame
) –New DataFrame with the column renamed.
Rename a column
# Create sample DataFrame
df = session.create_dataframe({
"age": [25, 30, 35],
"name": ["Alice", "Bob", "Charlie"]
})
# Rename a column
df.with_column_renamed("age", "age_in_years").show()
# Output:
# +------------+-------+
# |age_in_years| name|
# +------------+-------+
# | 25| Alice|
# | 30| Bob|
# | 35|Charlie|
# +------------+-------+
Rename multiple columns
# Rename multiple columns
df = (df
.with_column_renamed("age", "age_in_years")
.with_column_renamed("name", "full_name")
).show()
# Output:
# +------------+----------+
# |age_in_years|full_name |
# +------------+----------+
# | 25| Alice|
# | 30| Bob|
# | 35| Charlie|
# +------------+----------+
Source code in src/fenic/api/dataframe/dataframe.py
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 |
|
GroupedData
GroupedData(df: DataFrame, by: Optional[List[ColumnOrName]] = None)
Bases: BaseGroupedData
Methods for aggregations on a grouped DataFrame.
Initialize grouped data.
Parameters:
-
df
(DataFrame
) –The DataFrame to group.
-
by
(Optional[List[ColumnOrName]]
, default:None
) –Optional list of columns to group by.
Methods:
-
agg
–Compute aggregations on grouped data and return the result as a DataFrame.
Source code in src/fenic/api/dataframe/grouped_data.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
agg
agg(*exprs: Union[Column, Dict[str, str]]) -> DataFrame
Compute aggregations on grouped data and return the result as a DataFrame.
This method applies aggregate functions to the grouped data.
Parameters:
-
*exprs
(Union[Column, Dict[str, str]]
, default:()
) –Aggregation expressions. Can be:
- Column expressions with aggregate functions (e.g.,
count("*")
,sum("amount")
) - A dictionary mapping column names to aggregate function names (e.g.,
{"amount": "sum", "age": "avg"}
)
- Column expressions with aggregate functions (e.g.,
Returns:
-
DataFrame
(DataFrame
) –A new DataFrame with one row per group and columns for group keys and aggregated values
Raises:
-
ValueError
–If arguments are not Column expressions or a dictionary
-
ValueError
–If dictionary values are not valid aggregate function names
Count employees by department
# Group by department and count employees
df.group_by("department").agg(count("*").alias("employee_count"))
Multiple aggregations
# Multiple aggregations
df.group_by("department").agg(
count("*").alias("employee_count"),
avg("salary").alias("avg_salary"),
max("age").alias("max_age")
)
Dictionary style aggregations
# Dictionary style for simple aggregations
df.group_by("department", "location").agg({"salary": "avg", "age": "max"})
Source code in src/fenic/api/dataframe/grouped_data.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
|
SemanticExtensions
SemanticExtensions(df: DataFrame)
A namespace for semantic dataframe operators.
Initialize semantic extensions.
Parameters:
-
df
(DataFrame
) –The DataFrame to extend with semantic operations.
Methods:
-
join
–Performs a semantic join between two DataFrames using a natural language predicate.
-
sim_join
–Performs a semantic similarity join between two DataFrames using embedding expressions.
-
with_cluster_labels
–Cluster rows using K-means and add cluster metadata columns.
Source code in src/fenic/api/dataframe/semantic_extensions.py
30 31 32 33 34 35 36 |
|
join
join(other: DataFrame, join_instruction: str, examples: Optional[JoinExampleCollection] = None, model_alias: Optional[str] = None) -> DataFrame
Performs a semantic join between two DataFrames using a natural language predicate.
That evaluates to either true or false for each potential row pair.
The join works by: 1. Evaluating the provided join_instruction as a boolean predicate for each possible pair of rows 2. Including ONLY the row pairs where the predicate evaluates to True in the result set 3. Excluding all row pairs where the predicate evaluates to False
The instruction must reference exactly two columns, one from each DataFrame,
using the :left
and :right
suffixes to indicate column origin.
This is useful when row pairing decisions require complex reasoning based on a custom predicate rather than simple equality or similarity matching.
Parameters:
-
other
(DataFrame
) –The DataFrame to join with.
-
join_instruction
(str
) –A natural language description of how to match values.
- Must include one placeholder from the left DataFrame (e.g.
{resume_summary:left}
) and one from the right (e.g.{job_description:right}
). - This instruction is evaluated as a boolean predicate - pairs where it's
True
are included, pairs where it'sFalse
are excluded.
- Must include one placeholder from the left DataFrame (e.g.
-
examples
(Optional[JoinExampleCollection]
, default:None
) –Optional JoinExampleCollection containing labeled pairs (
left
,right
,output
) to guide the semantic join behavior. -
model_alias
(Optional[str]
, default:None
) –Optional alias for the language model to use for the mapping. If None, will use the language model configured as the default.
Returns:
-
DataFrame
(DataFrame
) –A new DataFrame containing only the row pairs where the join_instruction predicate evaluates to True.
Raises:
-
TypeError
–If
other
is not a DataFrame orjoin_instruction
is not a string. -
ValueError
–If the instruction format is invalid or references invalid columns.
Basic semantic join
# Match job listings with candidate resumes based on title/skills
# Only includes pairs where the predicate evaluates to True
df_jobs.semantic.join(df_resumes,
join_instruction="Given a candidate's resume_summary: {resume_summary:left} and a job description: {job_description:right}, does the candidate have the appropriate skills for the job?"
)
Semantic join with examples
# Improve join quality with examples
examples = JoinExampleCollection()
examples.create_example(JoinExample(
left="5 years experience building backend services in Python using asyncio, FastAPI, and PostgreSQL",
right="Senior Software Engineer - Backend",
output=True)) # This pair WILL be included in similar cases
examples.create_example(JoinExample(
left="5 years experience with growth strategy, private equity due diligence, and M&A",
right="Product Manager - Hardware",
output=False)) # This pair will NOT be included in similar cases
df_jobs.semantic.join(df_resumes,
join_instruction="Given a candidate's resume_summary: {resume_summary:left} and a job description: {job_description:right}, does the candidate have the appropriate skills for the job?",
examples=examples)
Source code in src/fenic/api/dataframe/semantic_extensions.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
|
sim_join
sim_join(other: DataFrame, left_on: ColumnOrName, right_on: ColumnOrName, k: int = 1, similarity_metric: SemanticSimilarityMetric = 'cosine', similarity_score_column: Optional[str] = None) -> DataFrame
Performs a semantic similarity join between two DataFrames using embedding expressions.
For each row in the left DataFrame, returns the top k
most semantically similar rows
from the right DataFrame based on the specified similarity metric.
Parameters:
-
other
(DataFrame
) –The right-hand DataFrame to join with.
-
left_on
(ColumnOrName
) –Expression or column representing embeddings in the left DataFrame.
-
right_on
(ColumnOrName
) –Expression or column representing embeddings in the right DataFrame.
-
k
(int
, default:1
) –Number of most similar matches to return per row.
-
similarity_metric
(SemanticSimilarityMetric
, default:'cosine'
) –Similarity metric to use: "l2", "cosine", or "dot".
-
similarity_score_column
(Optional[str]
, default:None
) –If set, adds a column with this name containing similarity scores. If None, the scores are omitted.
Returns:
-
DataFrame
–A DataFrame containing one row for each of the top-k matches per row in the left DataFrame.
-
DataFrame
–The result includes all columns from both DataFrames, optionally augmented with a similarity score column
-
DataFrame
–if
similarity_score_column
is provided.
Raises:
-
ValidationError
–If
k
is not positive or if the columns are invalid. -
ValidationError
–If
similarity_metric
is not one of "l2", "cosine", "dot"
Match queries to FAQ entries
# Match customer queries to FAQ entries
df_queries.semantic.sim_join(
df_faqs,
left_on=embeddings(col("query_text")),
right_on=embeddings(col("faq_question")),
k=1
)
Link headlines to articles
# Link news headlines to full articles
df_headlines.semantic.sim_join(
df_articles,
left_on=embeddings(col("headline")),
right_on=embeddings(col("content")),
k=3,
return_similarity_scores=True
)
Find similar job postings
# Find similar job postings across two sources
df_linkedin.semantic.sim_join(
df_indeed,
left_on=embeddings(col("job_title")),
right_on=embeddings(col("job_description")),
k=2
)
Source code in src/fenic/api/dataframe/semantic_extensions.py
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 |
|
with_cluster_labels
with_cluster_labels(by: ColumnOrName, num_clusters: int, label_column: str = 'cluster_label', centroid_column: Optional[str] = None) -> DataFrame
Cluster rows using K-means and add cluster metadata columns.
This method clusters rows based on the given embedding column or expression using K-means. It adds a new column with cluster assignments, and optionally includes the centroid embedding for each assigned cluster.
Parameters:
-
by
(ColumnOrName
) –Column or expression producing embeddings to cluster (e.g.,
embed(col("text"))
). -
num_clusters
(int
) –Number of clusters to compute (must be > 0).
-
label_column
(str
, default:'cluster_label'
) –Name of the output column for cluster IDs. Default is "cluster_label".
-
centroid_column
(Optional[str]
, default:None
) –If provided, adds a column with this name containing the centroid embedding for each row's assigned cluster.
Returns:
-
DataFrame
–A DataFrame with all original columns plus:
-
DataFrame
–<label_column>
: integer cluster assignment (0 to num_clusters - 1)
-
DataFrame
–<centroid_column>
: cluster centroid embedding, if specified
Raises:
-
ValidationError
–If num_clusters is not a positive integer
-
ValidationError
–If label_column is not a non-empty string
-
ValidationError
–If centroid_column is not a non-empty string
-
TypeMismatchError
–If the column is not an EmbeddingType
Basic clustering
# Cluster customer feedback and add cluster metadata
clustered_df = df.semantic.with_cluster_labels("feedback_embeddings", 5)
# Then use regular operations to analyze clusters
clustered_df.group_by("cluster_label").agg(count("*"), avg("rating"))
Filter outliers using centroids
# Cluster and filter out rows far from their centroid
clustered_df = df.semantic.with_cluster_labels("embeddings", 3, centroid_column="cluster_centroid")
clean_df = clustered_df.filter(
embedding.compute_similarity("embeddings", "cluster_centroid", metric="cosine") > 0.7
)
Source code in src/fenic/api/dataframe/semantic_extensions.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|