feature-factory 0.1.1-alpha

A high-performance feature engineering library for Rust powered by Apache DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! ## Categorical Encoding Transformers
//!
//! This module provides transformers (or encoders) that convert categorical features into numeric values.
//!
//! ### Available Transformers
//!
//! - [`OneHotEncoder`]: Expands each categorical column into multiple binary columns, one per distinct category.
//! - [`CountFrequencyEncoder`]: Replaces each category with its count (or frequency).
//! - [`OrdinalEncoder`]: Replaces each category with an ordinal (ordered integer) value.
//! - [`MeanEncoder`]: Replaces each category with the mean of a target variable.
//! - [`WoEEncoder`]: Replaces each category with its weight of evidence, calculated as the logarithm of the ratio of probabilities of “good” outcomes to “bad” outcomes.
//! - [`RareLabelEncoder`]: Groups infrequent categories into a single “rare” label.
//!
//! Each transformer returns a new DataFrame with the applied encodings.
//! Errors are returned as `FeatureFactoryError`, and results are wrapped in `FeatureFactoryResult`.

use crate::exceptions::{FeatureFactoryError, FeatureFactoryResult};
use crate::impl_transformer;
use arrow::array::Array;
use arrow::datatypes::DataType;
use datafusion::dataframe::DataFrame;
use datafusion::functions_aggregate::expr_fn::{avg, count};
use datafusion::logical_expr::{col, lit, Case as DFCase, Expr};
use std::collections::HashMap;

/// Validates that a column exists and is of Utf8 type.
fn validate_string_column(df: &DataFrame, col_name: &str) -> FeatureFactoryResult<()> {
    let field = df.schema().field_with_name(None, col_name).map_err(|_| {
        FeatureFactoryError::MissingColumn(format!("Column '{}' not found", col_name))
    })?;
    if field.data_type() != &DataType::Utf8 {
        return Err(FeatureFactoryError::InvalidParameter(format!(
            "Column '{}' must be of type Utf8, but found {:?}",
            col_name,
            field.data_type()
        )));
    }
    Ok(())
}

/// Validates that all columns in `cols` exist and are of Utf8 type.
fn validate_string_columns(df: &DataFrame, cols: &[String]) -> FeatureFactoryResult<()> {
    for col in cols {
        validate_string_column(df, col)?;
    }
    Ok(())
}

/// Validates that a column exists and is numeric (Float64 or Int64).
fn validate_numeric_column(df: &DataFrame, col_name: &str) -> FeatureFactoryResult<()> {
    let field = df.schema().field_with_name(None, col_name).map_err(|_| {
        FeatureFactoryError::MissingColumn(format!("Column '{}' not found", col_name))
    })?;
    match field.data_type() {
        DataType::Float64 | DataType::Int64 => Ok(()),
        dt => Err(FeatureFactoryError::InvalidParameter(format!(
            "Column '{}' must be numeric (Float64 or Int64), but found {:?}",
            col_name, dt
        ))),
    }
}

/// Sanitizes a category string so that it can be safely used as part of a column name.
/// Non-alphanumeric characters are replaced with underscores.
fn sanitize_category(cat: &str) -> String {
    cat.replace(|c: char| !c.is_alphanumeric(), "_")
}

/// Helper function to build a CASE WHEN expression given a mapping from category strings to values.
/// For each pair, the expression generated is:
/// `WHEN <col> = lit(<category>) THEN lit(<encoded_value>)`
/// If provided, `default` is used as the ELSE branch; otherwise, the original column is returned.
fn build_case_expr<T: Clone + 'static + datafusion::logical_expr::Literal>(
    col_name: &str,
    mapping: &[(String, T)],
    default: Option<Expr>,
) -> Expr {
    let when_then_expr = mapping
        .iter()
        .map(|(cat, val)| {
            (
                Box::new(col(col_name).eq(lit(cat.clone()))),
                Box::new(lit(val.clone())),
            )
        })
        .collect();
    Expr::Case(DFCase {
        expr: None,
        when_then_expr,
        else_expr: default.map(Box::new),
    })
}

/// Extract distinct string values for a given column from a DataFrame.
async fn extract_distinct_values(
    df: &DataFrame,
    col_name: &str,
) -> FeatureFactoryResult<Vec<String>> {
    // Validate that the column is of string type.
    validate_string_column(df, col_name)?;
    let distinct_df = df.clone().select(vec![col(col_name)])?.distinct()?;
    let batches = distinct_df
        .collect()
        .await
        .map_err(FeatureFactoryError::from)?;
    let mut values = Vec::new();
    for batch in batches {
        let array = batch
            .column(0)
            .as_any()
            .downcast_ref::<datafusion::arrow::array::StringArray>()
            .ok_or_else(|| {
                FeatureFactoryError::DataFusionError(datafusion::error::DataFusionError::Plan(
                    format!("Expected Utf8 array for column {}", col_name),
                ))
            })?;
        for i in 0..array.len() {
            if !array.is_null(i) {
                values.push(array.value(i).to_string());
            }
        }
    }
    Ok(values)
}

/// Extract a mapping (category -> count) for a given column by aggregating counts.
async fn extract_count_mapping(
    df: &DataFrame,
    col_name: &str,
) -> FeatureFactoryResult<HashMap<String, i64>> {
    validate_string_column(df, col_name)?;
    let grouped = df
        .clone()
        .aggregate(vec![col(col_name)], vec![count(col(col_name)).alias("cnt")])
        .map_err(FeatureFactoryError::from)?;
    let batches = grouped.collect().await.map_err(FeatureFactoryError::from)?;
    let mut map = HashMap::new();
    for batch in batches {
        let cat_array = batch
            .column(0)
            .as_any()
            .downcast_ref::<datafusion::arrow::array::StringArray>()
            .ok_or_else(|| {
                FeatureFactoryError::DataFusionError(datafusion::error::DataFusionError::Plan(
                    format!("Expected Utf8 array for column {}", col_name),
                ))
            })?;
        let count_array = batch
            .column(1)
            .as_any()
            .downcast_ref::<datafusion::arrow::array::Int64Array>()
            .ok_or_else(|| {
                FeatureFactoryError::DataFusionError(datafusion::error::DataFusionError::Plan(
                    "Expected Int64 array".into(),
                ))
            })?;
        for i in 0..batch.num_rows() {
            if !cat_array.is_null(i) {
                map.insert(cat_array.value(i).to_string(), count_array.value(i));
            }
        }
    }
    Ok(map)
}

/// Generic helper function to apply a mapping to each target column in a DataFrame.
/// For each field, if the column is in `target_cols` and a mapping is available via `mapping_fn`,
/// then the function replaces the column with a CASE–WHEN expression; otherwise, the original
/// column is retained. The `default_fn` closure produces a default expression for a given column name.
fn apply_mapping<T: Clone + 'static + datafusion::logical_expr::Literal>(
    df: DataFrame,
    target_cols: &[String],
    mapping_fn: impl Fn(&str) -> Option<Vec<(String, T)>>,
    default_fn: impl Fn(&str) -> Option<Expr>,
) -> FeatureFactoryResult<DataFrame> {
    let exprs: Vec<Expr> = df
        .schema()
        .fields()
        .iter()
        .map(|field| {
            let name = field.name();
            if target_cols.contains(name) {
                if let Some(map) = mapping_fn(name) {
                    build_case_expr(name, &map, default_fn(name)).alias(name)
                } else {
                    col(name)
                }
            } else {
                col(name)
            }
        })
        .collect();
    df.select(exprs).map_err(FeatureFactoryError::from)
}

/// Expands each categorical column into multiple binary columns, one per distinct category.
pub struct OneHotEncoder {
    pub columns: Vec<String>,
    /// Mapping from column name to list of distinct category values.
    pub categories: HashMap<String, Vec<String>>,
    fitted: bool,
}

impl OneHotEncoder {
    /// Create a new OneHotEncoder for the specified columns.
    pub fn new(columns: Vec<String>) -> Self {
        Self {
            columns,
            categories: HashMap::new(),
            fitted: false,
        }
    }

    /// Fit computes and stores distinct category values.
    pub async fn fit(&mut self, df: &DataFrame) -> FeatureFactoryResult<()> {
        validate_string_columns(df, &self.columns)?;
        for col_name in &self.columns {
            let values = extract_distinct_values(df, col_name).await?;
            self.categories.insert(col_name.clone(), values);
        }
        self.fitted = true;
        Ok(())
    }

    /// Transform applies one-hot encoding and returns a new DataFrame.
    pub fn transform(&self, df: DataFrame) -> FeatureFactoryResult<DataFrame> {
        if !self.fitted {
            return Err(FeatureFactoryError::FitNotCalled);
        }
        let mut exprs = vec![];
        for field in df.schema().fields() {
            exprs.push(col(field.name()));
        }
        for col_name in &self.columns {
            if let Some(cats) = self.categories.get(col_name) {
                for cat in cats {
                    let safe_cat = sanitize_category(cat);
                    let new_col_name = format!("{}_{}", col_name, safe_cat);
                    let case_expr = Expr::Case(DFCase {
                        expr: None,
                        when_then_expr: vec![(
                            Box::new(col(col_name).eq(lit(cat.clone()))),
                            Box::new(lit(1_i32)),
                        )],
                        else_expr: Some(Box::new(lit(0_i32))),
                    })
                    .alias(new_col_name);
                    exprs.push(case_expr);
                }
            }
        }
        df.select(exprs).map_err(FeatureFactoryError::from)
    }

    // This transformer is stateful.
    fn inherent_is_stateful(&self) -> bool {
        true
    }
}

/// Replaces each category in a column with its frequency.
pub struct CountFrequencyEncoder {
    pub columns: Vec<String>,
    /// Mapping from column to (category -> count)
    pub mapping: HashMap<String, HashMap<String, i64>>,
    fitted: bool,
}

impl CountFrequencyEncoder {
    /// Create a new CountFrequencyEncoder for the specified columns.
    pub fn new(columns: Vec<String>) -> Self {
        Self {
            columns,
            mapping: HashMap::new(),
            fitted: false,
        }
    }

    /// Fit computes counts for each category.
    pub async fn fit(&mut self, df: &DataFrame) -> FeatureFactoryResult<()> {
        validate_string_columns(df, &self.columns)?;
        for col_name in &self.columns {
            let map = extract_count_mapping(df, col_name).await?;
            self.mapping.insert(col_name.clone(), map);
        }
        self.fitted = true;
        Ok(())
    }

    /// Transform replaces each category with its count.
    pub fn transform(&self, df: DataFrame) -> FeatureFactoryResult<DataFrame> {
        if !self.fitted {
            return Err(FeatureFactoryError::FitNotCalled);
        }
        apply_mapping(
            df,
            &self.columns,
            |name| {
                self.mapping.get(name).map(|m| {
                    m.iter()
                        .map(|(k, &v)| (k.clone(), v))
                        .collect::<Vec<(String, i64)>>()
                })
            },
            |_| Some(lit(0_i64)),
        )
    }

    // This transformer is stateful.
    fn inherent_is_stateful(&self) -> bool {
        true
    }
}

/// Replaces each category with an ordinal (ordered integer) value.
/// Categories are sorted alphabetically and assigned increasing integers starting at 0.
pub struct OrdinalEncoder {
    pub columns: Vec<String>,
    /// Mapping from column to (category -> ordinal index)
    pub mapping: HashMap<String, HashMap<String, i64>>,
    fitted: bool,
}

impl OrdinalEncoder {
    /// Create a new OrdinalEncoder for the specified columns.
    pub fn new(columns: Vec<String>) -> Self {
        Self {
            columns,
            mapping: HashMap::new(),
            fitted: false,
        }
    }

    /// Fit computes the ordinal mapping.
    pub async fn fit(&mut self, df: &DataFrame) -> FeatureFactoryResult<()> {
        validate_string_columns(df, &self.columns)?;
        for col_name in &self.columns {
            let mut values = extract_distinct_values(df, col_name).await?;
            values.sort();
            let mapping = values
                .into_iter()
                .enumerate()
                .map(|(i, cat)| (cat, i as i64))
                .collect();
            self.mapping.insert(col_name.clone(), mapping);
        }
        self.fitted = true;
        Ok(())
    }

    /// Transform replaces each category with its ordinal index.
    pub fn transform(&self, df: DataFrame) -> FeatureFactoryResult<DataFrame> {
        if !self.fitted {
            return Err(FeatureFactoryError::FitNotCalled);
        }
        apply_mapping(
            df,
            &self.columns,
            |name| {
                self.mapping.get(name).map(|m| {
                    m.iter()
                        .map(|(k, &v)| (k.clone(), v))
                        .collect::<Vec<(String, i64)>>()
                })
            },
            |_| Some(lit(0_i64)),
        )
    }

    // This transformer is stateful.
    fn inherent_is_stateful(&self) -> bool {
        true
    }
}

/// Replaces each category with the mean of a target variable.
pub struct MeanEncoder {
    pub columns: Vec<String>,
    pub target: String,
    /// Mapping from column to (category -> mean)
    pub mapping: HashMap<String, HashMap<String, f64>>,
    fitted: bool,
}

impl MeanEncoder {
    /// Create a new MeanEncoder for the specified columns and target.
    pub fn new(columns: Vec<String>, target: String) -> Self {
        Self {
            columns,
            target,
            mapping: HashMap::new(),
            fitted: false,
        }
    }

    /// Fit computes the mean for each category.
    pub async fn fit(&mut self, df: &DataFrame) -> FeatureFactoryResult<()> {
        validate_string_columns(df, &self.columns)?;
        validate_numeric_column(df, &self.target)?;
        for col_name in &self.columns {
            let agg_df = df
                .clone()
                .aggregate(
                    vec![col(col_name)],
                    vec![avg(col(&self.target)).alias("mean")],
                )
                .map_err(FeatureFactoryError::from)?;
            let batches = agg_df.collect().await.map_err(FeatureFactoryError::from)?;
            let mut map = HashMap::new();
            for batch in batches {
                let cat_array = batch
                    .column(0)
                    .as_any()
                    .downcast_ref::<datafusion::arrow::array::StringArray>()
                    .ok_or_else(|| {
                        FeatureFactoryError::DataFusionError(
                            datafusion::error::DataFusionError::Plan(format!(
                                "Expected Utf8 array for column {}",
                                col_name
                            )),
                        )
                    })?;
                let mean_array = batch
                    .column(1)
                    .as_any()
                    .downcast_ref::<datafusion::arrow::array::Float64Array>()
                    .ok_or_else(|| {
                        FeatureFactoryError::DataFusionError(
                            datafusion::error::DataFusionError::Plan(
                                "Expected Float64 array".into(),
                            ),
                        )
                    })?;
                for i in 0..batch.num_rows() {
                    if !cat_array.is_null(i) {
                        map.insert(cat_array.value(i).to_string(), mean_array.value(i));
                    }
                }
            }
            self.mapping.insert(col_name.clone(), map);
        }
        self.fitted = true;
        Ok(())
    }

    /// Transform replaces each category with its mean.
    pub fn transform(&self, df: DataFrame) -> FeatureFactoryResult<DataFrame> {
        if !self.fitted {
            return Err(FeatureFactoryError::FitNotCalled);
        }
        apply_mapping(
            df,
            &self.columns,
            |name| {
                self.mapping.get(name).map(|m| {
                    m.iter()
                        .map(|(k, &v)| (k.clone(), v))
                        .collect::<Vec<(String, f64)>>()
                })
            },
            |_| Some(lit(0.0_f64)),
        )
    }

    // This transformer is stateful.
    fn inherent_is_stateful(&self) -> bool {
        true
    }
}

/// Replaces each category with its weight of evidence (WoE).
/// WoE is computed as ln((good_rate)/(bad_rate)), assuming a binary target.
pub struct WoEEncoder {
    pub columns: Vec<String>,
    pub target: String,
    /// Mapping from column to (category -> WoE)
    pub mapping: HashMap<String, HashMap<String, f64>>,
    fitted: bool,
}

impl WoEEncoder {
    /// Create a new WoEEncoder for the specified columns and target.
    pub fn new(columns: Vec<String>, target: String) -> Self {
        Self {
            columns,
            target,
            mapping: HashMap::new(),
            fitted: false,
        }
    }

    /// Fit computes the WoE for each category.
    pub async fn fit(&mut self, df: &DataFrame) -> FeatureFactoryResult<()> {
        validate_string_columns(df, &self.columns)?;
        validate_numeric_column(df, &self.target)?;
        let overall_df = df
            .clone()
            .aggregate(vec![], vec![count(col(&self.target)).alias("total")])
            .map_err(FeatureFactoryError::from)?;
        let overall_batches = overall_df
            .collect()
            .await
            .map_err(FeatureFactoryError::from)?;
        let _total = if let Some(batch) = overall_batches.first() {
            let total_array = batch
                .column(0)
                .as_any()
                .downcast_ref::<datafusion::arrow::array::Int64Array>()
                .ok_or_else(|| {
                    FeatureFactoryError::DataFusionError(datafusion::error::DataFusionError::Plan(
                        "Expected Int64 array".into(),
                    ))
                })?;
            total_array.value(0) as f64
        } else {
            return Err(FeatureFactoryError::DataFusionError(
                datafusion::error::DataFusionError::Plan("No data found".into()),
            ));
        };

        for col_name in &self.columns {
            let grouped = df
                .clone()
                .aggregate(
                    vec![col(col_name), col(&self.target)],
                    vec![count(lit(1)).alias("cnt")],
                )
                .map_err(FeatureFactoryError::from)?;
            let batches = grouped.collect().await.map_err(FeatureFactoryError::from)?;
            let mut cat_counts: HashMap<String, (f64, f64)> = HashMap::new(); // (good, bad)
            for batch in batches {
                let cat_array = batch
                    .column(0)
                    .as_any()
                    .downcast_ref::<datafusion::arrow::array::StringArray>()
                    .ok_or_else(|| {
                        FeatureFactoryError::DataFusionError(
                            datafusion::error::DataFusionError::Plan(format!(
                                "Expected Utf8 array for column {}",
                                col_name
                            )),
                        )
                    })?;
                let target_array = batch
                    .column(1)
                    .as_any()
                    .downcast_ref::<datafusion::arrow::array::Int64Array>()
                    .ok_or_else(|| {
                        FeatureFactoryError::DataFusionError(
                            datafusion::error::DataFusionError::Plan("Expected Int64 array".into()),
                        )
                    })?;
                let count_array = batch
                    .column(2)
                    .as_any()
                    .downcast_ref::<datafusion::arrow::array::Int64Array>()
                    .ok_or_else(|| {
                        FeatureFactoryError::DataFusionError(
                            datafusion::error::DataFusionError::Plan("Expected Int64 array".into()),
                        )
                    })?;
                for i in 0..batch.num_rows() {
                    if !cat_array.is_null(i) {
                        let cat = cat_array.value(i).to_string();
                        let target_val = target_array.value(i);
                        let cnt = count_array.value(i) as f64;
                        let entry = cat_counts.entry(cat).or_insert((0.0, 0.0));
                        if target_val == 1 {
                            entry.0 += cnt;
                        } else {
                            entry.1 += cnt;
                        }
                    }
                }
            }
            let mut mapping = HashMap::new();
            for (cat, (good, bad)) in cat_counts {
                let woe = ((good + 1e-6) / (bad + 1e-6)).ln();
                mapping.insert(cat, woe);
            }
            self.mapping.insert(col_name.clone(), mapping);
        }
        self.fitted = true;
        Ok(())
    }

    /// Transform replaces each category with its computed WoE.
    pub fn transform(&self, df: DataFrame) -> FeatureFactoryResult<DataFrame> {
        if !self.fitted {
            return Err(FeatureFactoryError::FitNotCalled);
        }
        apply_mapping(
            df,
            &self.columns,
            |name| {
                self.mapping.get(name).map(|m| {
                    m.iter()
                        .map(|(k, &v)| (k.clone(), v))
                        .collect::<Vec<(String, f64)>>()
                })
            },
            |_| Some(lit(0.0_f64)),
        )
    }

    // This transformer is stateful.
    fn inherent_is_stateful(&self) -> bool {
        true
    }
}

/// Groups infrequent categories into a single “rare” label.
pub struct RareLabelEncoder {
    pub columns: Vec<String>,
    pub threshold: f64, // frequency threshold (between 0 and 1)
    /// Mapping from column to (category -> encoded label)
    pub mapping: HashMap<String, HashMap<String, String>>,
    fitted: bool,
}

impl RareLabelEncoder {
    /// Create a new RareLabelEncoder for the specified columns and threshold.
    pub fn new(columns: Vec<String>, threshold: f64) -> Self {
        Self {
            columns,
            threshold,
            mapping: HashMap::new(),
            fitted: false,
        }
    }

    /// Fit computes frequencies and marks infrequent categories as "rare".
    pub async fn fit(&mut self, df: &DataFrame) -> FeatureFactoryResult<()> {
        if self.threshold < 0.0 || self.threshold > 1.0 {
            return Err(FeatureFactoryError::InvalidParameter(format!(
                "Threshold {} must be between 0 and 1",
                self.threshold
            )));
        }
        validate_string_columns(df, &self.columns)?;
        let total_df = df
            .clone()
            .aggregate(vec![], vec![count(lit(1)).alias("total")])
            .map_err(FeatureFactoryError::from)?;
        let total_batches = total_df
            .collect()
            .await
            .map_err(FeatureFactoryError::from)?;
        let total = if let Some(batch) = total_batches.first() {
            let total_array = batch
                .column(0)
                .as_any()
                .downcast_ref::<datafusion::arrow::array::Int64Array>()
                .ok_or_else(|| {
                    FeatureFactoryError::DataFusionError(datafusion::error::DataFusionError::Plan(
                        "Expected Int64 array".into(),
                    ))
                })?;
            total_array.value(0) as f64
        } else {
            return Err(FeatureFactoryError::DataFusionError(
                datafusion::error::DataFusionError::Plan("No data found".into()),
            ));
        };

        for col_name in &self.columns {
            let grouped = df
                .clone()
                .aggregate(vec![col(col_name)], vec![count(col(col_name)).alias("cnt")])
                .map_err(FeatureFactoryError::from)?;
            let batches = grouped.collect().await.map_err(FeatureFactoryError::from)?;
            let mut map = HashMap::new();
            for batch in batches {
                let cat_array = batch
                    .column(0)
                    .as_any()
                    .downcast_ref::<datafusion::arrow::array::StringArray>()
                    .ok_or_else(|| {
                        FeatureFactoryError::DataFusionError(
                            datafusion::error::DataFusionError::Plan(format!(
                                "Expected Utf8 array for column {}",
                                col_name
                            )),
                        )
                    })?;
                let cnt_array = batch
                    .column(1)
                    .as_any()
                    .downcast_ref::<datafusion::arrow::array::Int64Array>()
                    .ok_or_else(|| {
                        FeatureFactoryError::DataFusionError(
                            datafusion::error::DataFusionError::Plan("Expected Int64 array".into()),
                        )
                    })?;
                for i in 0..batch.num_rows() {
                    if !cat_array.is_null(i) {
                        let cat = cat_array.value(i).to_string();
                        let cnt = cnt_array.value(i) as f64;
                        let freq = cnt / total;
                        let encoded = if freq < self.threshold {
                            "rare".to_string()
                        } else {
                            cat.clone()
                        };
                        map.insert(cat, encoded);
                    }
                }
            }
            self.mapping.insert(col_name.clone(), map);
        }
        self.fitted = true;
        Ok(())
    }

    /// Transform replaces each category with its encoded label.
    pub fn transform(&self, df: DataFrame) -> FeatureFactoryResult<DataFrame> {
        if !self.fitted {
            return Err(FeatureFactoryError::FitNotCalled);
        }
        apply_mapping(
            df,
            &self.columns,
            |name| {
                self.mapping.get(name).map(|m| {
                    m.iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect::<Vec<(String, String)>>()
                })
            },
            |name| Some(col(name)),
        )
    }

    // This transformer is stateful.
    fn inherent_is_stateful(&self) -> bool {
        true
    }
}

// Implement the Transformer trait for the transformers in this module.
impl_transformer!(OneHotEncoder);
impl_transformer!(CountFrequencyEncoder);
impl_transformer!(OrdinalEncoder);
impl_transformer!(MeanEncoder);
impl_transformer!(WoEEncoder);
impl_transformer!(RareLabelEncoder);