# pysparky.transformations.general

*module*

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L1-L1)

## pysparky.transformations.general.agg_apply

*function*

```python
def agg_apply(df: DataFrame, agg_exprs: Dict[str, Column]) -> DataFrame
```

Apply aggregation expressions and return a DataFrame.

**Parameters**

- `df` (`DataFrame`) — The input Spark DataFrame.
- `agg_exprs` (`Dict[str, Column]`) — A dictionary where keys are the aliases for the aggregated columns                            and values are the Spark aggregation expressions (Columns).

**Returns**

- `DataFrame` (`DataFrame`) — A DataFrame containing the aggregated results.

> **Example**
>
> ```python
> >>> df = spark.createDataFrame([(1, "A"), (2, "A"), (3, "B")], ["value", "category"])
> >>> agg_exprs = {
> ...     "total_value": F.sum("value"),
> ...     "max_value": F.max("value"),
> ...     "count": F.count("*")
> ... }
> >>> result = agg_apply(df, agg_exprs)
> >>> result.show()
> +-----------+---------+-----+
> |total_value|max_value|count|
> +-----------+---------+-----+
> |          6|        3|    3|
> +-----------+---------+-----+
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L311-L339)

## pysparky.transformations.general.apply_cols

*function*

```python
def apply_cols(sdf: DataFrame, col_func: Callable, cols: list[str] | None = None, **kwargs) -> DataFrame
```

Apply a function to specified columns of a Spark DataFrame.

**Parameters**

- `sdf` (`DataFrame`) — The input Spark DataFrame.
- `col_func` (`callable`) — The function to apply to each column.
- `cols` (`list[str]`) (default: `None`) — List of column names to apply the function to.                         If None, applies to all columns. Defaults to None.

**Returns**

- `DataFrame` (`DataFrame`) — A new Spark DataFrame with the function applied to the specified columns.

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L11-L31)

## pysparky.transformations.general.distinct_value_counts_map

*function*

```python
def distinct_value_counts_map(sdf: DataFrame, column_name: str) -> DataFrame
```

Get distinct values from a DataFrame column as a map with their counts.

**Parameters**

- `sdf` (`DataFrame`) — The input Spark DataFrame.
- `column_name` (`str`) — The name of the column to process.

**Returns**

- `DataFrame` (`DataFrame`) — A DataFrame containing a single column with a map of distinct values and their counts.

> **Example**
>
> ```python
> >>> data = [("Alice",), ("Bob",), ("Alice",), ("Eve",), (None,)]
> >>> sdf = spark.createDataFrame(data, ["name"])
> >>> result = distinct_value_counts_map(sdf, "name")
> >>> result.show(truncate=False)
> +-------------------------------------------+
> |name_map                                   |
> +-------------------------------------------+
> |{Alice -> 2, Bob -> 1, Eve -> 1, NONE -> 1}|
> +-------------------------------------------+
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L137-L172)

## pysparky.transformations.general.execute_transformation_blueprint

*function*

```python
def execute_transformation_blueprint(sdf: DataFrame, blueprint: dict[str, Column]) -> DataFrame
```

Executes a transformation blueprint on a Spark DataFrame.

The transformation blueprint is a dictionary where keys are column names
and values are the corresponding transformations to apply. The function
applies each transformation in the order specified by the blueprint and
returns the resulting DataFrame with the transformed columns.

A transformation_blueprint is a dictionary that the
key: new column name
value: Column function

**Parameters**

- `sdf` (`DataFrame`) — The input DataFrame to be transformed.
- `blueprint` (`Dict[str, Column]`) — A dictionary of column names as keys and transformation functions as values.

**Returns**

- `DataFrame` (`DataFrame`) — The resulting DataFrame with the transformed columns.

> **Example**
>
> ```python
> >>> df = spark.createDataFrame([(1,), (2,)], ["value"])
> >>> blueprint = {"value_plus_1": F.col("value") + 1}
> >>> df.transform(execute_transformation_blueprint, blueprint).show()
> +------------+
> |value_plus_1|
> +------------+
> |           2|
> |           3|
> +------------+
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L267-L308)

## pysparky.transformations.general.filters

*function*

```python
def filters(sdf: DataFrame, conditions: list[Column], operator_: str = 'and') -> DataFrame
```

Apply multiple filter conditions to a Spark DataFrame.

This function takes a Spark DataFrame, a list of conditions, and an optional
operator. It returns a new DataFrame with all conditions applied using the
specified operator.

**Parameters**

- `sdf` (`pyspark.sql.DataFrame`) — The input Spark DataFrame to be filtered.
- `conditions` (`list[pyspark.sql.Column]`) — A list of Column expressions representing the filter conditions.
- `operator_` (`Callable`) (default: `'and'`) — The operator to use for combining conditions. Defaults to `and_`. Valid options are `and_` and `or_`.

**Returns**

- (`DataFrame`) — pyspark.sql.DataFrame: A new DataFrame with all filter conditions applied.

**Raises**

- `ValueError` — If an unsupported operator is provided.

> **Example**
>
> ```python
> >>> from pyspark.sql.functions import col
> >>> df = spark.createDataFrame([(1, 'a'), (2, 'b'), (3, 'c')], ['id', 'letter'])
> >>> conditions = [col('id') > 1, col('letter').isin(['b', 'c'])]
> 
> # Filter using AND (default behavior)
> >>> filtered_df_and = filters(df, conditions)
> >>> filtered_df_and.show()
> +---+------+
> | id|letter|
> +---+------+
> |  2|     b|
> |  3|     c|
> +---+------+
> 
> # Filter using OR
> >>> filtered_df_or = filters(df, conditions, or_)
> >>> filtered_df_or.show()
> +---+------+
> | id|letter|
> +---+------+
> |  2|     b|
> |  3|     c|
> |  1|     a|
> +---+------+
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L71-L134)

## pysparky.transformations.general.get_unique_values

*function*

```python
def get_unique_values(df1: DataFrame, df2: DataFrame, column_name: str) -> DataFrame
```

Unions two DataFrames and returns a DataFrame with unique values.

**Parameters**

- `df1` (`DataFrame`) — First DataFrame.
- `df2` (`DataFrame`) — Second DataFrame.
- `column_name` (`str`) — The column name containing the values.

**Returns**

- `DataFrame` (`DataFrame`) — A DataFrame with unique values.

> **Example**
>
> ```python
> >>> df1 = spark.createDataFrame([(1,), (2,), (3,)], ["value"])
> >>> df2 = spark.createDataFrame([(3,), (4,), (5,)], ["value"])
> >>> unique_values = get_unique_values(df1, df2, "value")
> >>> unique_values.sort("value").show()
> +-----+
> |value|
> +-----+
> |    1|
> |    2|
> |    3|
> |    4|
> |    5|
> +-----+
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L175-L209)

## pysparky.transformations.general.order_and_aggregate_events

*function*

```python
def order_and_aggregate_events(df: DataFrame, id_col: str, value_col: str, record_no_col: str, values_array_col: str, record_nos_array_col: str, sort_asc: bool = True) -> DataFrame
```

Group events by id, order by record_no, and aggregate into arrays.

**Parameters**

- `df` (`DataFrame`) — The input DataFrame.
- `id_col` (`str`) — The column name to group events by.
- `value_col` (`str`) — The column name for values to aggregate.
- `record_no_col` (`str`) — The column name for record numbers to sort by.
- `values_array_col` (`str`) — The column name for the aggregated values array.
- `record_nos_array_col` (`str`) — The column name for the aggregated record numbers array.
- `sort_asc` (`bool`) (default: `True`) — Whether to sort the arrays in ascending order. Defaults to True.

**Returns**

- `DataFrame` (`DataFrame`) — A DataFrame with events aggregated into arrays and ordered by record_no.

> **Example**
>
> ```python
> >>> data = [
> ...     ("A", "val1", 2),
> ...     ("A", "val2", 1),
> ...     ("B", "val3", 1),
> ... ]
> >>> df = spark.createDataFrame(data, ["id", "value", "record_no"])
> >>> result = order_and_aggregate_events(df, "id", "value", "record_no", "values", "record_nos")
> >>> result.show(truncate=False)
> +---+------------+----------+
> |id |values      |record_nos|
> +---+------------+----------+
> |A  |[val2, val1]|[1, 2]    |
> |B  |[val3]      |[1]       |
> +---+------------+----------+
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L341-L415)

## pysparky.transformations.general.set_columns_to_null_based_on_condition

*function*

```python
def set_columns_to_null_based_on_condition(df: DataFrame, condition_column: str, condition_value: str, target_columns: tuple[str]) -> DataFrame
```

Sets specified columns to null based on a condition in the given DataFrame.

**Parameters**

- `df` (`DataFrame`) — The input DataFrame.
- `condition_column` (`str`) — The name of the column containing the condition value.
- `condition_value` (`str`) — The value indicating the condition to set columns to null.
- `target_columns` (`Tuple[str]`) — The tuple of columns to be set as null if the condition value is found.

**Returns**

- `DataFrame` (`DataFrame`) — The updated DataFrame with specified columns set to null based on the condition.

> **Example**
>
> ```python
> >>> data = [
> ...     (1, 0, 0, 0),
> ...     (2, 0, 1, 0),
> ...     (3, 1, 1, 1),
> ...     (4, 1, 0, 1),
> ...     (5, 0, 0, 0),
> ... ]
> >>> columns = ["ID", "Dummy1", "Dummy2", "Dummy3"]
> >>> df = spark.createDataFrame(data, columns)
> >>> condition_column = "Dummy1"
> >>> condition_value = 1
> >>> target_columns = ("Dummy2", "Dummy3")
> >>> result_df = set_columns_to_null_based_on_condition(df, condition_column, condition_value, target_columns)
> >>> result_df.show()
> +---+------+------+------+
> | ID|Dummy1|Dummy2|Dummy3|
> +---+------+------+------+
> |  1|     0|     0|     0|
> |  2|     0|     1|     0|
> |  3|     1|  null|  null|
> |  4|     1|  null|  null|
> |  5|     0|     0|     0|
> +---+------+------+------+
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L212-L264)

## pysparky.transformations.general.transforms

*function*

```python
def transforms(sdf: DataFrame, transformations: list[tuple[Callable, dict]]) -> DataFrame
```

Apply a series of transformations to a Spark DataFrame.

**Parameters**

- `sdf` (`DataFrame`) — The input Spark DataFrame to be transformed.
- `transformations` (`list`) — A list of transformations, where each transformation is a tuple             containing a function and a dictionary of keyword arguments to apply the function to.

**Returns**

- `DataFrame` (`DataFrame`) — The transformed Spark DataFrame.

> **Example**
>
> ```python
> >>> def add_one(sdf, col_name):
> ...     return sdf.withColumn(col_name, F.col(col_name) + 1)
> >>> df = spark.createDataFrame([(1,), (2,)], ["value"])
> >>> transformations = [(add_one, {"col_name": "value"})]
> >>> df.transform(transforms, transformations).show()
> +-----+
> |value|
> +-----+
> |    2|
> |    3|
> +-----+
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/transformations/general.py#L34-L68)
