---
title: "Pass NaN and empty strings to an ONNX imputer in C#"
url: https://recursiveai.org/onemodel/cookbook/pass-missing-values-to-onnx-imputer/
description: "Pass float.NaN and an empty string to a fitted scikit-learn imputer in ONNX. Use the missing-value markers the model expects and read the result in C#."
version: "1.5.0"
---

# Pass NaN and empty strings to an ONNX imputer 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/pass-missing-values-to-onnx-imputer/pass-missing-values-to-onnx-imputer.zip)

Fill missing values with `impute.onnx` (in the zip). Send `float.NaN` for age and `""` for city.
The zip includes `export.py`; see [how to recreate the model](#how-do-i-export-a-fitted-imputer-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("impute.onnx");
using var inputs = new ModelInputs();
inputs.Add<float>("age", [float.NaN]);
inputs.Add("city", [""]);
using var result = model.Run(inputs);
var row = result.Floats("transformed_column");
Console.WriteLine(string.Join(", ", row));
```

[The example](https://recursiveai.org/onemodel/cookbook/pass-missing-values-to-onnx-imputer/pass-missing-values-to-onnx-imputer.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 `impute.onnx` from the zip into that project folder before running it.

Prints:

```text
40, 2
```

## Full program

```csharp
using RecursiveAI.OneModel;

using var model = Model.Load("impute.onnx");
using var inputs = new ModelInputs();
inputs.Add<float>("age", [float.NaN]);
inputs.Add("city", [""]);
using var result = model.Run(inputs);
var row = result.Floats("transformed_column");
Console.WriteLine($"Age: {row[0]}");
Console.WriteLine($"City code: {row[1]}");
```

`dotnet run` prints:

```text
Age: 40
City code: 2
```

The fitted age imputer substitutes the median of 20, 40, and 60. The city imputer substitutes `unknown` for `""`; the following ordinal encoder maps `paris`, `rome`, and `unknown` to 0, 1, and 2. The two numbers are features, not predictions.

If you omit `city` instead of sending an empty string, inference throws `SessionException` because the required input is missing.

## Variations

To keep a known city but still fill the missing age, change only the city input. The result is `40, 1`, because the encoder maps `rome` to 1.

```csharp
inputs.Add("city", ["rome"]);
```

## 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/) · [Run an ONNX ColumnTransformer](https://recursiveai.org/onemodel/cookbook/run-onnx-column-transformer-with-mixed-columns/)

---

## The short answer

Send `float.NaN` and `""` as actual column values when the exported pipeline was fitted with those markers. Don’t leave out the column. `ModelInputs` gives each column its own name and type, and the graph fills the missing entries before any downstream encoder or estimator runs.

## What counts as a missing value in SimpleImputer?

`missing_values` is the marker to replace. It isn’t the replacement value. In the [scikit-learn `SimpleImputer` reference](https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html), the numeric default is `np.nan`; `strategy="median"` learns the replacement during fitting. The sample was fitted on 20, 40, and 60, so it uses 40. That stays true even if a later batch contains different ages or only missing ages. A real zero isn’t replaced by this model. If your export was fitted with another marker, use that exact value rather than assuming all imputers treat `NaN` the same way.

## How do I export a fitted imputer to ONNX?

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.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OrdinalEncoder
from skl2onnx import to_onnx

frame = pd.DataFrame({
    "age": np.array([20, 40, 60], dtype=np.float32),
    "city": ["rome", "paris", ""],
})
age = SimpleImputer(strategy="median")
city = make_pipeline(
    SimpleImputer(
        missing_values="", strategy="constant",
        fill_value="unknown",
    ),
    OrdinalEncoder(),
)
model = ColumnTransformer([
    ("numeric", age, ["age"]),
    ("category", city, ["city"]),
]).fit(frame)
graph = to_onnx(model, frame[:1], target_opset=17)
with open("impute.onnx", "wb") as file:
    file.write(graph.SerializeToString())
```

## Can an ONNX imputer fill missing categorical strings?

Yes, if the exported graph includes a string replacement step. The `Imputer` operator in [OneModel’s `ai.onnx.ml` operators](https://recursiveai.org/onemodel/docs/ops-ml/) takes numbers, not strings. For the city column, skl2onnx exports a lookup step that detects the empty string and substitutes `unknown`, not an ONNX `Imputer` operator. The Python `SimpleImputer` configuration for the city column is `missing_values=""`, `strategy="constant"`, and `fill_value="unknown"`. `OrdinalEncoder` runs afterward, which is why you read a numeric city code instead of the string `unknown`.

An empty string isn’t a C# `null`, a space, or a category absent from the training set. The app supplying the inputs has to decide which source fields are missing and normalize them to the model’s marker. Don’t trim or replace meaningful text just to make the model accept it; match how the data was prepared at training time.

## Why are my missing values not being replaced in ONNX?

Check what the graph receives and which transformer was exported. For your own model, run this after `Model.Load` to print both sets of names and types (see [Session.cs, lines 49–53](https://github.com/recursive-ai-oss/onemodel-csharp/blob/c4f8bdcd456e17d74b9b1d89cfc250e4ed4c8de6/src/OneModel/Graph/Session.cs#L49-L53) and [TensorInfo.cs, lines 28–39](https://github.com/recursive-ai-oss/onemodel-csharp/blob/c4f8bdcd456e17d74b9b1d89cfc250e4ed4c8de6/src/OneModel/Graph/TensorInfo.cs#L28-L39)):

```csharp
foreach (var input in model.Session.Inputs)
    Console.WriteLine($"Input {input}");
foreach (var output in model.Session.Outputs)
    Console.WriteLine($"Output {output}");
```

If your C# code substitutes `0` for a missing age, the graph gets a valid zero and never sees the `NaN`. If the city goes in as a single space, it’s not the empty string marker. This model’s categorical branch is fitted with `OrdinalEncoder` on a specific vocabulary; a new city and a missing city are different cases. Choose and export the behavior you want for unrecognized categories rather than silently turning them into missing values.

If the full pipeline ends in a classifier, its declared outputs may only be labels and probabilities. To see the filled values directly, export the fitted preprocessing stage separately, as this example does. That makes it possible to check the imputer without reasoning backward from a final prediction.
