---
title: Column Selection
jupyter: python3
html-table-processing: none
---

The `columns=` argument for methods like `~~GT.tab_spanner()`, `~~GT.cols_move()`, and `~~GT.tab_style` allows a range of options for selecting columns.

The simplest approach is just a list of strings with the exact column names. However, we can specify columns using any of the following:

* a single string column name.
* an integer for the column's position.
* a list of strings or integers.
* a **Polars** selector.
* a function that takes a string and returns `True` or `False`.

```{python}
from great_tables import GT
from great_tables.data import exibble

lil_exibble = exibble[["num", "char", "fctr", "date", "time"]].head(4)
gt_ex = GT(lil_exibble)

gt_ex
```

## Using integers

We can use a list of strings or integers to select columns by name or position, respectively.

```{python}
gt_ex.cols_move_to_start(columns=["date", 1, -1])
```

Note the code above moved the following columns:

* The string `"date"` matched the column of the same name.
* The integer `1` matched the second column (this is similar to list indexing).
* The integer `-1` matched the last column.

Moreover, the order of the list defines the order of selected columns. In this case, `"data"` was the first entry, so it's the very first column in the new table.

## Using **Polars** selectors

When using a **Polars** DataFrame, you can select columns using [**Polars** selectors](https://pola-rs.github.io/polars/py-polars/html/reference/selectors.html). The example below uses **Polars** selectors to move all columns that start with `"c"` or `"f"` to the start of the table.

```{python}
import polars as pl
import polars.selectors as cs

pl_df = pl.from_pandas(lil_exibble)

GT(pl_df).cols_move_to_start(columns=cs.starts_with("c") | cs.starts_with("f"))
```

In general, selection should match the behaviors of the **Polars** `DataFrame.select()` method.

```{python}
pl_df.select(cs.starts_with("c") | cs.starts_with("f")).columns
```

See the [Selectors page in the polars docs](https://pola-rs.github.io/polars/py-polars/html/reference/selectors.html) for more information on this.


## Using functions

A function can be used to select columns. It should take a column name as a string and return `True` or `False`.

```{python}
gt_ex.cols_move_to_start(columns=lambda x: "c" in x)
```
