Keep Columns
Keep only specified columns in a DataFrame or Arrow Table.
Keep Columns
Processing
This brick filters the input data (DataFrame or Arrow Table) to retain only the columns explicitly specified in the options or input. The resulting filtered data can be outputted in various formats (Pandas DataFrame, Polars DataFrame, or PyArrow Table). If no columns are specified for filtering, the input data is returned unchanged.
Inputs
- data
- The input data (Pandas DataFrame, Polars DataFrame, or PyArrow Table) that needs to be filtered down to a specific set of columns.
- columns (optional)
- A list of string names representing the columns that should be kept in the output data structure. This input, if connected, overrides the list defined in the options menu.
- regex pattern (optional)
- A regular expression pattern used to match and select columns. If provided, this method of selection overrides the explicit
columnslist.
Inputs Types
| Input | Types |
|---|---|
data |
DataFrame, ArrowTable |
columns |
List |
regex pattern |
Str |
You can check the list of supported types here: Available Type Hints.
Outputs
- result
- The resulting data structure containing only the specified columns. The type of the output depends on the selected
Output Formatoption.
Outputs Types
| Output | Types |
|---|---|
result |
DataFrame, ArrowTable |
You can check the list of supported types here: Available Type Hints.
Options
The Keep Columns brick contains some changeable options:
- List of Columns
- A list of column names (as strings) that must be present in the output data.
- Regex Pattern
- A regular expression used to select columns. If this option is provided, it takes precedence over the explicit column list.
- Output Format
- Specifies the desired data format for the output structure. Choices include
pandas(Pandas DataFrame),polars(Polars DataFrame), orarrow(PyArrow Table). Defaults topandas. - Safe Mode
- If enabled, the brick will ignore any column names listed that do not exist in the input data, instead of raising an error and stopping the flow. Defaults to
False. - Verbose
- If enabled, detailed logging messages regarding the operation steps (e.g., input format detection, column counts, query execution) are displayed. Defaults to
True.
import logging
import duckdb
import pandas as pd
import polars as pl
import pyarrow as pa
import re
from coded_flows.types import Union, List, DataFrame, ArrowTable, Str, Bool
from coded_flows.utils import CodedFlowsLogger
logger = CodedFlowsLogger(name="Keep Columns", level=logging.INFO)
def _coalesce(*values):
return next((v for v in values if v is not None), None)
def _sanitize_identifier(identifier):
"""
Sanitize SQL identifier by escaping special characters.
Handles double quotes and other problematic characters.
"""
return identifier.replace('"', '""')
def keep_columns(
data: Union[DataFrame, ArrowTable],
columns: List = None,
regex_pattern: Str = None,
options=None,
) -> Union[DataFrame, ArrowTable]:
options = options or {}
verbose = options.get("verbose", True)
columns = _coalesce(columns, options.get("columns", []))
regex_pattern = _coalesce(regex_pattern, options.get("regex_pattern", ""))
output_format = options.get("output_format", "pandas")
safe_mode = options.get("safe_mode", False)
result = None
try:
selection_mode = None
if regex_pattern:
selection_mode = "regex"
elif columns and len(columns) > 0:
selection_mode = "list"
verbose and logger.info(
f"Starting column filter operation. Mode: {selection_mode}."
)
if selection_mode == "list" and (not isinstance(columns, list)):
verbose and logger.error(f"Invalid columns format!")
raise ValueError("Columns must be provided as a list!")
data_type = None
if isinstance(data, pd.DataFrame):
data_type = "pandas"
elif isinstance(data, pl.DataFrame):
data_type = "polars"
elif isinstance(data, (pa.Table, pa.lib.Table)):
data_type = "arrow"
if data_type is None:
verbose and logger.error(
f"Input data must be a pandas DataFrame, Polars DataFrame, or Arrow Table"
)
raise ValueError(
"Input data must be a pandas DataFrame, Polars DataFrame, or Arrow Table"
)
verbose and logger.info(f"Detected input format: {data_type}.")
conn = duckdb.connect(":memory:")
conn.register("input_table", data)
column_info = conn.execute("DESCRIBE input_table").fetchall()
all_columns = [col[0] for col in column_info]
columns_to_keep = []
skipped_count = 0
if selection_mode == "regex":
try:
pattern = re.compile(regex_pattern)
columns_to_keep = [col for col in all_columns if pattern.search(col)]
verbose and logger.info(
f"Regex pattern '{regex_pattern}' matched {len(columns_to_keep)} columns."
)
except re.error:
conn.close()
verbose and logger.error(f"Invalid regex pattern provided.")
raise ValueError(f"Invalid regex pattern: {regex_pattern}")
elif selection_mode == "list":
if not safe_mode:
missing_columns = [col for col in columns if col not in all_columns]
if missing_columns:
verbose and logger.error(
f"Columns not found in data: {missing_columns}"
)
conn.close()
raise ValueError(f"Columns not found in data: {missing_columns}")
for col in columns:
if col in all_columns:
columns_to_keep.append(col)
elif safe_mode:
verbose and logger.warning(
f"Safe mode: Skipping non-existent column: {col}"
)
skipped_count += 1
if not columns_to_keep:
verbose and logger.error(
f"No valid columns to keep! Result would be empty."
)
conn.close()
raise ValueError(
"No valid columns to keep! Ensure columns exist or regex matches."
)
select_parts = [f'"{_sanitize_identifier(col)}"' for col in columns_to_keep]
select_clause = ", ".join(select_parts)
query = f"SELECT {select_clause} FROM input_table"
verbose and logger.info(
f"Executing query to keep {len(columns_to_keep)} columns."
)
if output_format == "pandas":
result = conn.execute(query).df()
verbose and logger.info(f"Converted result to pandas DataFrame.")
elif output_format == "polars":
result = conn.execute(query).pl()
verbose and logger.info(f"Converted result to Polars DataFrame.")
elif output_format == "arrow":
result = conn.execute(query).fetch_arrow_table()
verbose and logger.info(f"Converted result to Arrow Table.")
else:
conn.close()
verbose and logger.error(f"Unsupported output format: {output_format}")
raise ValueError(f"Unsupported output format: {output_format}")
conn.close()
verbose and logger.info(
f"Operation completed. Kept {len(columns_to_keep)} columns."
)
except Exception as e:
verbose and logger.error(f"Error during column filter operation.")
raise
return result
Brick Info
- pandas
- pyarrow
- polars[pyarrow]
- duckdb