---
title: "Run an ONNX ColumnTransformer in C#"
url: https://recursiveai.org/onemodel/cookbook/run-onnx-column-transformer-with-mixed-columns/
description: "Run a fitted scikit-learn ColumnTransformer in C#. Pass float, int64, and string columns as separate ONNX inputs and read the class and its probability."
version: "1.5.0"
---

# Run an ONNX ColumnTransformer in C#

**OneModel** is a free, open-source .NET library from Recursive AI for running ONNX models, including scikit-learn pipelines and XGBoost and LightGBM models. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModel) · [GitHub](https://github.com/recursive-ai-oss/onemodel-csharp) · [Docs](https://recursiveai.org/onemodel/docs/) · [Download example (.zip)](https://recursiveai.org/onemodel/cookbook/run-onnx-column-transformer-with-mixed-columns/run-onnx-column-transformer-with-mixed-columns.zip)

Pass numbers and text as separate columns to the scikit-learn pipeline in `mixed.onnx` (in the zip).
The zip includes `export.py`; see [how to recreate the model](#how-do-i-convert-a-columntransformer-pipeline-to-onnx).

```shell
dotnet add package RecursiveAI.OneModel
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneModel;

using var model = Model.Load("mixed.onnx");
using var inputs = new ModelInputs();
inputs.Add<float>("age", [54f]);
inputs.Add<long>("visits", [7L]);
inputs.Add("plan", ["plus"]);
using var result = model.Run(inputs);
Console.WriteLine(
    result.Int64s("output_label")[0]);
```

[The example](https://recursiveai.org/onemodel/cookbook/run-onnx-column-transformer-with-mixed-columns/run-onnx-column-transformer-with-mixed-columns.zip) is the full program below: unzip it and `dotnet run`. To run only the code above, paste it into Program.cs of a new `dotnet new console` project and `dotnet run`.

If you’re pasting the snippet into a new project, copy `mixed.onnx` from the zip into that project folder before running it.

Prints:

```text
1
```

## Full program

```csharp
using RecursiveAI.OneModel;

using var model = Model.Load("mixed.onnx");
using var inputs = new ModelInputs();
inputs.Add<float>("age", [54f]);
inputs.Add<long>("visits", [7L]);
inputs.Add("plan", ["plus"]);
using var result = model.Run(inputs);
var label = result.Int64s("output_label")[0];
var chance = result.Int64Maps(
    "output_probability")[0][label];
Console.WriteLine(FormattableString.Invariant(
    $"Class {label}: {chance:F4}"));
```

`dotnet run` prints:

```text
Class 1: 0.7650
```

`mixed.onnx` scales `age` and `visits`, one-hot encodes `plan` (one flag per category), then runs logistic regression. This row is age 54, seven visits, and plan `plus`. The full program prints the predicted class and its probability to four decimal places.

If you pass `visits` as `float`, inference throws `SessionException`: the input is declared as `int64`, which is `long` in C#.

## Variations

Inspect the declared input names and kinds before swapping in another export. This replaces the input and prediction code after `Model.Load`.

```csharp
foreach (var input in model.Session.Inputs)
    Console.WriteLine(
        $"{input.Name}: {input.Kind}");
```

The model declares `age` and `visits` as numeric tensors and `plan` as a string tensor.

## Related recipes

[ONNX with multiple inputs and outputs](https://recursiveai.org/onemodel/cookbook/named-inputs-and-outputs/) · [Run a scikit-learn random forest with ONNX](https://recursiveai.org/onemodel/cookbook/run-scikit-learn-onnx-classifier/) · [Pass NaN and empty strings to an ONNX imputer](https://recursiveai.org/onemodel/cookbook/pass-missing-values-to-onnx-imputer/)

---

## The short answer

Pass each original column to `ModelInputs` under its ONNX name: `Add<float>` for `age`, `Add<long>` for `visits`, and the string overload of `Add` for `plan`. Call `Model.Run` once with all three. You don’t need to scale values or create dummy columns in C#: the fitted preprocessing steps are in the graph.

## How do I convert a ColumnTransformer pipeline to ONNX?

Export the fitted pipeline, not just its final classifier. This example fits two `StandardScaler` steps and a `OneHotEncoder(handle_unknown="ignore")` on a DataFrame, then feeds their combined features to `LogisticRegression`. The training columns are `age` (`float32`), `visits` (`int64`), and `plan` (strings). The export uses the same DataFrame schema:

To recreate the model, install the export dependencies in a Python environment:

```shell
python -m pip install scikit-learn==1.9.1
python -m pip install skl2onnx==1.20.0
python -m pip install numpy==2.5.5 onnx==1.23.2
python -m pip install pandas==3.1.2
```

Save this as `export.py` and run `python export.py` in the project folder. It replaces the sample `.onnx` file. You don’t need Python to run the C# example with the supplied model.

```python
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import (
    OneHotEncoder, StandardScaler,
)
from skl2onnx import to_onnx

frame = pd.DataFrame({
    "age": np.array(
        [24, 28, 31, 55, 62, 67], dtype=np.float32
    ),
    "visits": np.array(
        [1, 3, 2, 8, 6, 9], dtype=np.int64
    ),
    "plan": [
        "basic", "basic", "plus",
        "plus", "basic", "plus",
    ],
})
columns = ColumnTransformer([
    ("age", StandardScaler(), ["age"]),
    ("visits", StandardScaler(), ["visits"]),
    ("plan", OneHotEncoder(
        handle_unknown="ignore"
    ), ["plan"]),
])
model = make_pipeline(columns, LogisticRegression())
model.fit(frame, [0, 0, 0, 1, 1, 1])
graph = to_onnx(model, frame[:1], target_opset=17)
with open("mixed.onnx", "wb") as file:
    file.write(graph.SerializeToString())
```

A representative row describes the inputs; it doesn’t refit the pipeline. See the [skl2onnx ColumnTransformer example](https://onnx.ai/sklearn-onnx/auto_examples/plot_complex_pipeline.html) for an explicit schema with `initial_types` instead. If you pass an array of one common dtype instead of a DataFrame, you’re no longer describing three separately typed columns.

## What shape do mixed ONNX inputs need?

In this export every input has shape `[N, 1]`, meaning one value per record. The model leaves `N` open, so OneModel infers it from the length of each array. To score two records, pass two ages, two visit counts, and two plan names in the same row order. The association is by input name across columns and by index within a column. Passing the first person’s age alongside the second person’s plan creates a different record, not a shape error.

Check `model.Session.Inputs` for the declared names, types, and dimensions when using a different export. A column that happens to contain whole numbers still needs `Add<float>` if the graph declares it as `float`, and a named `int64` input doesn’t take C# `int` values. The [pipeline guide](https://recursiveai.org/onemodel/docs/guide-sklearn-pipelines/) describes when OneModel can infer a shape and when you have to pass one.

## How do I read the predicted class and its probability?

The example keeps skl2onnx’s default `ZipMap` output. Each record gets one predicted class in `output_label` and one probability map in `output_probability`. The keys are class labels, not positions in an array. Use `Int64Maps` for integer keys and `StringMaps` for string keys. If you export with `zipmap=False`, inspect the new output name and read its numeric tensor instead; map accessors are for the default map output.
