# Chalk Python SDK Reference: Array Functions
source: https://docs.chalk.ai/api-docs#section-array-functions

## `array_agg(expr)`
source: https://docs.chalk.ai/api-docs#array_agg

Extract a single-column [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) into a list of values for that column.

**Parameters**

- `expr`: `Underscore | Any`
  The expression to extract into a list.

**Examples**

```python
from datetime import datetime
import chalk.functions as F
from chalk import DataFrame
from chalk.features import _, features
@features
class Merchant:
    id: str
    events: "DataFrame[FraudEvent]"
    fraud_codes: list[str] = F.array_agg(_.events[_.is_fraud == True, _.tag])
@features
class FraudEvent:
    id: int
    tag: str
    is_fraud: bool
    mer_id: Merchant.id
```

## `array_average(expr)`
source: https://docs.chalk.ai/api-docs#array_average

Calculates the arithmetic mean of the numerical values of an array.

**Parameters**

- `expr`: `Underscore | Any`
  The array to average

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class StudentGrades:
    id: str
    test_scores: list[float]
    average_score: float = F.array_average(_.test_scores)
```

## `array_count_value(expr, value)`
source: https://docs.chalk.ai/api-docs#array_count_value

Returns the count of a string value in an array.

**Parameters**

- `expr`: `Underscore`
  The string array.
- `value`: `str | Underscore`
  The value to count in the array

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class Bookstore:
   id: str
   inventory_types: list[str] = ["fiction", "non-fiction", "fiction", "fiction", "non-fiction"]
   books: str = F.array_count_value(_.inventory_types, "fiction")
```

## `array_cum_sum(array)`
source: https://docs.chalk.ai/api-docs#array_cum_sum

Calculate cumulative sum of array elements.

**Parameters**

- `array`: `Underscore`
  The numeric array to calculate cumulative sum for.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class MetricsAnalysis:
    id: str
    daily_revenues: list[float]
    cumulative_revenues: list[float] = F.array_cum_sum(_.daily_revenues)
```

## `array_distinct(arr)`
source: https://docs.chalk.ai/api-docs#array_distinct

Returns an array with distinct elements from the input array.

**Parameters**

- `arr`: `Underscore`
  The array to extract distinct elements from.

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class User:
   id: str
   tags: list[str]
   unique_tags: list[str] = F.array_distinct(_.tags)
```

## `array_duplicates(array)`
source: https://docs.chalk.ai/api-docs#array_duplicates

Returns duplicate elements in the array.

**Parameters**

- `array`: `Underscore`
  The array to find duplicates in.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class CustomerAnalysis:
    id: str
    purchase_categories: list[str]
    repeat_categories: list[str] = F.array_duplicates(_.purchase_categories)
```

## `array_except(left_array, right_array)`
source: https://docs.chalk.ai/api-docs#array_except

Returns elements in left array that are not in right array.

**Parameters**

- `left_array`: `Underscore`
  The array to subtract from.
- `right_array`: `Underscore`
  The array containing elements to remove.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class FeatureComparison:
    id: str
    all_features: list[str]
    active_features: list[str]
    disabled_features: list[str] = F.array_except(_.all_features, _.active_features)
```

## `array_has_duplicates(array)`
source: https://docs.chalk.ai/api-docs#array_has_duplicates

Checks if the array contains duplicate elements.

**Parameters**

- `array`: `Underscore`
  The array to check for duplicates.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class DataQuality:
    id: str
    user_ids: list[int]
    has_duplicate_users: bool = F.array_has_duplicates(_.user_ids)
```

## `array_intersect(left_array, right_array)`
source: https://docs.chalk.ai/api-docs#array_intersect

Returns common elements between two arrays.

**Parameters**

- `left_array`: `Underscore`
  The first array.
- `right_array`: `Underscore`
  The second array.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class CustomerSegmentation:
    id: str
    current_interests: list[str]
    past_purchases: list[str]
    relevant_interests: list[str] = F.array_intersect(_.current_interests, _.past_purchases)
```

## `array_join(arr, delimiter)`
source: https://docs.chalk.ai/api-docs#array_join

Concatenate the elements of an array into a single string with a delimiter.

**Parameters**

- `arr`: `Underscore | list[Any]`
  The array to join. The values will be casted to strings if they are not already strings.
- `delimiter`: `str`
  The delimiter to use to join the elements of the array.

**Examples**

```python
from datetime import datetime
import chalk.functions as F
from chalk.features import _, features
@features
class Wordle:
   id: str
   words: list[str]
   words_str: str = F.array_join(_.words, ", ")
```

## `array_max(arr)`
source: https://docs.chalk.ai/api-docs#array_max

Returns the maximum value in an array.

**Parameters**

- `arr`: `Underscore`
  The array to find the maximum value in.

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class Wordle:
   id: str
   words: list[str] = ["crane", "kayak", "plots", "fight", "exact", "zebra", "hello", "world"]
   longest_word: str = F.array_max(_.words)
```

## `array_median(expr)`
source: https://docs.chalk.ai/api-docs#array_median

Calculates the median of the numerical values of an array.

**Parameters**

- `expr`: `Underscore | Any`
  The array to take the median of

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class HousingMarket:
    id: str
    property_prices: list[float]
    median_price: float = F.array_median(_.property_prices)
```

## `array_min(arr)`
source: https://docs.chalk.ai/api-docs#array_min

Returns the minimum value in an array.

**Parameters**

- `arr`: `Underscore`
  The array to find the minimum value in.

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class Wordle:
   id: str
   words: list[str] = ["crane", "kayak", "plots", "fight", "exact", "zebra", "hello", "world"]
   shortest_word: str = F.array_min(_.words)
```

## `array_mode(expr, tiebreak)`
source: https://docs.chalk.ai/api-docs#array_mode

Calculates the mode of the numerical values of an array.

**Parameters**

- `expr`: `Underscore | Any`
  The array to take the mode of; if there are multiple modes, undefined which one is returned
- `tiebreak`: `'FIRST' | 'MAX' | 'MIN'` = `'FIRST'`
  If there are multiple modes, which mode to select. Take the example list `[0, 2, 1, 2, 3, 3, 1, 4]` with multimodes 1, 2, 3:

  `"FIRST"` will return 2, as 2 occurs before 1 and 3 in the list;

  `"MAX"` will return 3, the max of the multimodes;

  `"MIN"` will return 1, the min of the multimodes;

  Defaults to `"FIRST"` (the behavior of python's `statistics.mode()`)

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class SurveyAnalysis:
    id: str
    responses: list[int]
    most_common_response: int = F.array_mode(_.responses)
    highest_mode: int = F.array_mode(_.responses, tiebreak="MAX")
```

## `array_normalize(array, p)`
source: https://docs.chalk.ai/api-docs#array_normalize

Calculate the p-norm of the array. For instance:

- for l1 normalization, set p=1.0
- for l2 normalization, set p=2.0 (default)

**Parameters**

- `array`: `Underscore`
  The numeric array to normalize.
- `p`: `Underscore | float | None` = `None`

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class ProbabilityModel:
    id: str
    raw_scores: list[float]
    probabilities: list[float] = F.array_normalize(_.raw_scores)
```

## `array_position(array, element)`
source: https://docs.chalk.ai/api-docs#array_position

Find the position of an element in the array (1-based indexing).

**Parameters**

- `array`: `Underscore`
  The array to search in.
- `element`: `Underscore`
  The element to find.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class RankingAnalysis:
    id: str
    ranked_products: list[str]
    target_product: str
    product_rank: int = F.array_position(_.ranked_products, _.target_product)
```

## `array_remove(array, element)`
source: https://docs.chalk.ai/api-docs#array_remove

Remove all occurrences of an element from the array.

**Parameters**

- `array`: `Underscore`
  The array to remove elements from.
- `element`: `Underscore`
  The element to remove.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class DataCleaning:
    id: str
    transaction_types: list[str]
    filtered_types: list[str] = F.array_remove(_.transaction_types, "test")
```

## `array_sample_stddev(expr)`
source: https://docs.chalk.ai/api-docs#array_sample_stddev

Calculates the sample standard deviation of the numerical values of an array. Divides square difference from means by N-1 as opposed to N

**Parameters**

- `expr`: `Underscore | Any`
  The array to calculate the sample standard deviation

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class ExperimentResults:
    id: str
    sample_measurements: list[float]
    sample_stddev: float = F.array_sample_stddev(_.sample_measurements)
```

## `array_sort(expr, descending)`
source: https://docs.chalk.ai/api-docs#array_sort

Returns an array which has the sorted order of the input array. Null elements will be placed at the end of the returned array.

**Parameters**

- `expr`: `Underscore | Any`
  The array to sort
- `descending`: `bool` = `False`
  Whether to sort the array in descending order. Defaults to False.

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class LeaderBoard:
    id: str
    scores: list[int]
    sorted_scores_asc: list[int] = F.array_sort(_.scores)
    sorted_scores_desc: list[int] = F.array_sort(_.scores, descending=True)
```

## `array_stddev(expr)`
source: https://docs.chalk.ai/api-docs#array_stddev

Calculates the standard deviation of the numerical values of an array.

**Parameters**

- `expr`: `Underscore | Any`
  The array to calculate the standard deviation

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class SensorData:
    id: str
    temperature_readings: list[float]
    temp_stddev: float = F.array_stddev(_.temperature_readings)
```

## `array_sum(expr)`
source: https://docs.chalk.ai/api-docs#array_sum

Calculates the sum of the numerical values of an array.

**Parameters**

- `expr`: `Underscore | Any`
  The array to sum

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class Transaction:
    id: str
    line_items: list[float]
    total_amount: float = F.array_sum(_.line_items)
```

## `arrays_overlap(left_array, right_array)`
source: https://docs.chalk.ai/api-docs#arrays_overlap

Check if two arrays have common elements.

**Parameters**

- `left_array`: `Underscore`
  The first array.
- `right_array`: `Underscore`
  The second array.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class UserCompatibility:
    id: str
    user_interests: list[str]
    recommended_interests: list[str]
    has_overlap: bool = F.arrays_overlap(_.user_interests, _.recommended_interests)
```

## `cardinality(arr)`
source: https://docs.chalk.ai/api-docs#cardinality

Returns the number of elements in an array.

**Parameters**

- `arr`: `Underscore`
  The array to count the number of elements in.

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class Wordle:
   id: str
   words: list[str]
   num_words: int = F.cardinality(_.words)
```

## `contains(arr, value)`
source: https://docs.chalk.ai/api-docs#contains

Returns whether the array contains the value.

**Parameters**

- `arr`: `Underscore | list[Any] | set[Any]`
  The array to check for the value.
- `value`: `Any`
  The value to check for in the array.

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class APIRequest:
   id: str
   headers: list[str]
   has_user_agent: bool = F.contains(_.headers, "User-Agent")
```

## `element_at(arr, index)`
source: https://docs.chalk.ai/api-docs#element_at

Returns the element of an array at the given index.

**Parameters**

- `arr`: `Underscore | list[Any]`
  The array.
- `index`: `int | Underscore`
  The index to extract the element from (0-indexed).

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class Wordle:
   id: str
   words: list[str] = ["crane", "kayak", "plots", "fight", "exact", "zebra", "hello", "world"]
   first_word: str = F.element_at(_.words, 0)
```

## `flatten(array)`
source: https://docs.chalk.ai/api-docs#flatten

Flatten nested arrays into a single-level array.

**Parameters**

- `array`: `Underscore`
  The nested array to flatten.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class DataProcessing:
    id: str
    nested_categories: list[list[str]]
    all_categories: list[str] = F.flatten(_.nested_categories)
```

## `head(dataframe, n)`
source: https://docs.chalk.ai/api-docs#head

Returns the first n items from a dataframe or has-many

**Parameters**

- `dataframe`: `Underscore | Any`
  the has-many from which the first n items are taken
- `n`: `Underscore | int`
  how many items to take

**Examples**

```python
from datetime import datetime
import chalk.functions as F
from chalk import windowed, DataFrame, Windowed
from chalk.features import _, features, Primary
@features
class Merchant:
    id: str
@features
class ConfirmedFraud:
    id: int
    trn_dt: datetime
    is_fraud: int
    mer_id: Merchant.id
@features
class MerchantFraud:
    mer_id: Primary[Merchant.id]
    merchant: Merchant
    confirmed_fraud: DataFrame[ConfirmedFraud] = dataframe(
        lambda: ConfirmedFraud.mer_id == MerchantFraud.mer_id,
    )
    first_five_merchant_window_fraud: Windowed[list[int]] = windowed(
        "1d",
        "30d",
        expression=F.head(_.confirmed_fraud[_.trn_dt > _.chalk_window, _.id, _.is_fraud == 1], 5)
    )
```

## `max_by(dataframe, sort)`
source: https://docs.chalk.ai/api-docs#max_by

Returns the row in a dataframe or has-many relationship with the maximum value in a given column.

**Parameters**

- `dataframe`: `Underscore | Any`
  The [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) or has-many relationship to find the maximum value in. This [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) should refer to _exactly_ one result column, which should reference the returned value. The [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) can include any necessary filters.
- `sort`: `Underscore | Any`
  The ordering to sort by. A single column, a tuple of columns to order by in precedence order, or a [`sort_order`](https://docs.chalk.ai/api-docs#sort_order) call when a key needs an explicit direction or null placement.

**Returns**

**Examples**

```python
from chalk import DataFrame, _
from chalk.features import features, has_one
import chalk.functions as F
@features
class Transaction:
    id: int
    amount: float
    user_id: int
@features
class User:
    id: int
    transactions: DataFrame[Transaction] = has_many(lambda: User.id == Transaction.user_id)
    biggest_transfer_id: int = F.max_by(
        _.transactions[_.category == "ach", _.id],
        _.amount,
    )
    biggest_transfer: Transaction = has_one(
        lambda: Transaction.id == User.biggest_transfer_id
    )
```

## `max_by_n(dataframe, sort, n)`
source: https://docs.chalk.ai/api-docs#max_by_n

Returns the rows in a dataframe or has-many relationship with the maximum n values in a given column. This is equivalent to `sort_by(sort_col, DESC).head(n)[result_col]`

**Parameters**

- `dataframe`: `Underscore | Any`
  The [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) or has-many relationship to find the maximum value in. This [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) should refer to _exactly_ one result column, which should reference the returned value. The [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) can include any necessary filters.
- `sort`: `Underscore | Any`
  The ordering to sort by. A single column, a tuple of columns to order by in precedence order, or a [`sort_order`](https://docs.chalk.ai/api-docs#sort_order) call when a key needs an explicit direction or null placement.
- `n`: `int`
  The number of rows to return.

**Returns**

**Examples**

```python
from datetime import datetime
from chalk import DataFrame, _
from chalk.features import features, has_one
import chalk.functions as F
@features
class Transaction:
    id: int
    processed_date: datetime
    amount: float
    user_id: "User.id"
@features
class User:
    id: int
    transactions: DataFrame[Transaction]
    last_3_txns_avg: float = F.array_average(
        F.max_by_n(
            _.transactions[_.amount],
            _.processed_date,
            3,
        )
    )
```

## `min_by(dataframe, sort)`
source: https://docs.chalk.ai/api-docs#min_by

Returns the row in a dataframe or has-many relationship with the minimum value in a given column.

**Parameters**

- `dataframe`: `Underscore | Any`
  The [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) or has-many relationship to find the minimum value in. This [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) should refer to _exactly_ one result column, which should reference the returned value. The [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) can include any necessary filters.
- `sort`: `Underscore | Any`
  The ordering to sort by. A single column, a tuple of columns to order by in precedence order, or a [`sort_order`](https://docs.chalk.ai/api-docs#sort_order) call when a key needs an explicit direction or null placement.

**Returns**

**Examples**

```python
from chalk import DataFrame, _
from chalk.features import features, has_one
import chalk.functions as F
@features
class Transaction:
    id: int
    amount: float
    user_id: int
@features
class User:
    id: int
    transactions: DataFrame[Transaction] = has_many(lambda: User.id == Transaction.user_id)
    smallest_transfer_id: int = F.min_by(
        _.transactions[_.category == "ach", _.id],
        _.amount,
    )
    smallest_transfer: Transaction = has_one(
        lambda: Transaction.id == User.smallest_transfer_id
    )
```

## `min_by_n(dataframe, sort, n)`
source: https://docs.chalk.ai/api-docs#min_by_n

Returns the rows in a dataframe or has-many relationship with the minimum n values in a given column. This is equivalent to `sort_by(sort_col, ASC).head(n)[result_col]`

**Parameters**

- `dataframe`: `Underscore | Any`
  The [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) or has-many relationship to find the minimum value in. This [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) should refer to _exactly_ one result column, which should reference the returned value. The [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) can include any necessary filters.
- `sort`: `Underscore | Any`
  The ordering to sort by. A single column, a tuple of columns to order by in precedence order, or a [`sort_order`](https://docs.chalk.ai/api-docs#sort_order) call when a key needs an explicit direction or null placement.
- `n`: `int`
  The number of rows to return.

**Returns**

**Examples**

```python
from datetime import datetime
from chalk import DataFrame, _
from chalk.features import features, has_one
import chalk.functions as F
@features
class Transaction:
    id: int
    processed_date: datetime
    amount: float
    user_id: "User.id"
@features
class User:
    id: int
    transactions: DataFrame[Transaction]
    earliest_3_txns_avg: float = F.array_average(
        F.min_by_n(
            _.transactions[_.amount],
            _.processed_date,
            3,
        )
    )
```

## `remove_nulls(array)`
source: https://docs.chalk.ai/api-docs#remove_nulls

Remove all null values from the array.

**Parameters**

- `array`: `Underscore`
  The array to remove nulls from.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class DataCleaning:
    id: str
    raw_scores: list[float | None]
    clean_scores: list[float] = F.remove_nulls(_.raw_scores)
```

## `sequence(start, stop, step)`
source: https://docs.chalk.ai/api-docs#sequence

Generate a sequence of integers.

**Parameters**

- `start`: `Underscore | int`
  The starting value (inclusive).
- `stop`: `Underscore | int`
  The ending value (inclusive).
- `step`: `Underscore | int` = `1`
  The increment between values (default: 1).

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class IndexGeneration:
    id: str
    batch_size: int
    indices: list[int] = F.sequence(1, _.batch_size)
```

## `shuffle(array)`
source: https://docs.chalk.ai/api-docs#shuffle

Randomly shuffle array elements.

**Parameters**

- `array`: `Underscore`
  The array to shuffle.

**Returns**

**Examples**

```python
import chalk.functions as F
from chalk.features import _, features
@features
class RecommendationSystem:
    id: str
    product_list: list[str]
    shuffled_recommendations: list[str] = F.shuffle(_.product_list)
```

## `slice(arr, offset, length)`
source: https://docs.chalk.ai/api-docs#slice

Returns a subset of the original array.

**Parameters**

- `arr`: `Underscore | list[Any]`
  The array to slice
- `offset`: `Underscore | int`
  Starting index of the slice (0-indexed). If negative, slice starts from the end of the array
- `length`: `Underscore | int`
  The length of the slice.

**Examples**

```python
from datetime import datetime
import chalk.functions as F
from chalk.features import _, features
@features
class Wordle:
   id: str
   words: list[str] = ["crane", "kayak", "plots", "fight", "exact", "zebra", "hello", "world"]
   three_most_recent_words: list[str] = F.slice(_.words, -3, 3) # computes ["zebra", "hello", "world"]
```
