pandrs 0.3.0

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! Data operations functionality for OptimizedDataFrame

use rayon::prelude::*;
use std::collections::HashMap;

use super::core::{ColumnView, OptimizedDataFrame};
use crate::column::{
    BooleanColumn, Column, ColumnTrait, ColumnType, Float64Column, Int64Column, StringColumn,
};
use crate::error::{Error, Result};
use crate::index::{DataFrameIndex, Index, IndexTrait};

impl OptimizedDataFrame {
    /// Select columns (as a new DataFrame)
    pub fn select(&self, columns: &[&str]) -> Result<Self> {
        let mut result = Self::new();

        for &name in columns {
            let column_idx = self
                .column_indices
                .get(name)
                .ok_or_else(|| Error::ColumnNotFound(name.to_string()))?;

            let column = self.columns[*column_idx].clone();
            result.add_column(name.to_string(), column)?;
        }

        // Copy index
        if let Some(ref idx) = self.index {
            result.index = Some(idx.clone());
        }

        Ok(result)
    }

    /// Filter rows (as a new DataFrame)
    pub fn filter(&self, condition_column: &str) -> Result<Self> {
        // Get condition column
        let column_idx = self
            .column_indices
            .get(condition_column)
            .ok_or_else(|| Error::ColumnNotFound(condition_column.to_string()))?;

        let condition = &self.columns[*column_idx];

        // Verify that the condition column is Boolean type
        if let Column::Boolean(bool_col) = condition {
            // Collect indices of rows where the value is true
            let mut indices = Vec::new();
            for i in 0..bool_col.len() {
                if let Ok(Some(true)) = bool_col.get(i) {
                    indices.push(i);
                }
            }

            // Create a new DataFrame
            let mut result = Self::new();

            // Filter each column
            for (i, name) in self.column_names.iter().enumerate() {
                let column = &self.columns[i];

                let filtered_column = match column {
                    Column::Int64(col) => {
                        let mut filtered_data = Vec::with_capacity(indices.len());
                        for &idx in &indices {
                            if let Ok(Some(val)) = col.get(idx) {
                                filtered_data.push(val);
                            } else {
                                filtered_data.push(0); // Default value
                            }
                        }
                        Column::Int64(Int64Column::new(filtered_data))
                    }
                    Column::Float64(col) => {
                        let mut filtered_data = Vec::with_capacity(indices.len());
                        for &idx in &indices {
                            if let Ok(Some(val)) = col.get(idx) {
                                filtered_data.push(val);
                            } else {
                                filtered_data.push(0.0); // Default value
                            }
                        }
                        Column::Float64(Float64Column::new(filtered_data))
                    }
                    Column::String(col) => {
                        let mut filtered_data = Vec::with_capacity(indices.len());
                        for &idx in &indices {
                            if let Ok(Some(val)) = col.get(idx) {
                                filtered_data.push(val.to_string());
                            } else {
                                filtered_data.push(String::new()); // Default value
                            }
                        }
                        Column::String(StringColumn::new(filtered_data))
                    }
                    Column::Boolean(col) => {
                        let mut filtered_data = Vec::with_capacity(indices.len());
                        for &idx in &indices {
                            if let Ok(Some(val)) = col.get(idx) {
                                filtered_data.push(val);
                            } else {
                                filtered_data.push(false); // Default value
                            }
                        }
                        Column::Boolean(BooleanColumn::new(filtered_data))
                    }
                };

                result.add_column(name.clone(), filtered_column)?;
            }

            Ok(result)
        } else {
            Err(Error::ColumnTypeMismatch {
                name: condition_column.to_string(),
                expected: ColumnType::Boolean,
                found: condition.column_type(),
            })
        }
    }

    /// Filter by specified row indices (internal helper)
    pub(crate) fn filter_by_indices(&self, indices: &[usize]) -> Result<Self> {
        let mut result = Self::new();

        // Filter each column
        for (i, name) in self.column_names.iter().enumerate() {
            let column = &self.columns[i];

            let filtered_column = match column {
                Column::Int64(col) => {
                    let filtered_data: Vec<i64> = indices
                        .iter()
                        .filter_map(|&idx| {
                            if idx < col.len() {
                                if let Ok(Some(val)) = col.get(idx) {
                                    Some(val)
                                } else {
                                    Some(0) // Default value
                                }
                            } else {
                                None
                            }
                        })
                        .collect();
                    Column::Int64(Int64Column::new(filtered_data))
                }
                Column::Float64(col) => {
                    let filtered_data: Vec<f64> = indices
                        .iter()
                        .filter_map(|&idx| {
                            if idx < col.len() {
                                if let Ok(Some(val)) = col.get(idx) {
                                    Some(val)
                                } else {
                                    Some(0.0) // Default value
                                }
                            } else {
                                None
                            }
                        })
                        .collect();
                    Column::Float64(Float64Column::new(filtered_data))
                }
                Column::String(col) => {
                    let filtered_data: Vec<String> = indices
                        .iter()
                        .filter_map(|&idx| {
                            if idx < col.len() {
                                if let Ok(Some(val)) = col.get(idx) {
                                    Some(val.to_string())
                                } else {
                                    Some(String::new()) // Default value
                                }
                            } else {
                                None
                            }
                        })
                        .collect();
                    Column::String(StringColumn::new(filtered_data))
                }
                Column::Boolean(col) => {
                    let filtered_data: Vec<bool> = indices
                        .iter()
                        .filter_map(|&idx| {
                            if idx < col.len() {
                                if let Ok(Some(val)) = col.get(idx) {
                                    Some(val)
                                } else {
                                    Some(false) // Default value
                                }
                            } else {
                                None
                            }
                        })
                        .collect();
                    Column::Boolean(BooleanColumn::new(filtered_data))
                }
            };

            result.add_column(name.clone(), filtered_column)?;
        }

        // Copy index
        if let Some(ref idx) = self.index {
            result.index = Some(idx.clone());
        }

        Ok(result)
    }

    /// Get the first n rows
    pub fn head(&self, n: usize) -> Result<Self> {
        let n = std::cmp::min(n, self.row_count);
        let indices: Vec<usize> = (0..n).collect();
        self.filter_by_indices(&indices)
    }

    /// Get the last n rows
    pub fn tail(&self, n: usize) -> Result<Self> {
        let n = std::cmp::min(n, self.row_count);
        let start = self.row_count.saturating_sub(n);
        let indices: Vec<usize> = (start..self.row_count).collect();
        self.filter_by_indices(&indices)
    }

    /// Convert DataFrame to "long format" (melt operation)
    ///
    /// Converts multiple columns into a single "variable" column and "value" column.
    /// This implementation prioritizes performance.
    ///
    /// # Arguments
    /// * `id_vars` - Column names to keep unchanged (identifier columns)
    /// * `value_vars` - Column names to convert (value columns). If None, all columns except id_vars
    /// * `var_name` - Name for the variable column (default: "variable")
    /// * `value_name` - Name for the value column (default: "value")
    ///
    /// # Returns
    /// * `Result<Self>` - DataFrame converted to long format
    pub fn melt(
        &self,
        id_vars: &[&str],
        value_vars: Option<&[&str]>,
        var_name: Option<&str>,
        value_name: Option<&str>,
    ) -> Result<Self> {
        // Set default values for arguments
        let var_name = var_name.unwrap_or("variable");
        let value_name = value_name.unwrap_or("value");

        // If value_vars is not specified, use all columns except id_vars
        let value_vars = if let Some(vars) = value_vars {
            vars.to_vec()
        } else {
            self.column_names
                .iter()
                .filter(|name| !id_vars.contains(&name.as_str()))
                .map(|s| s.as_str())
                .collect()
        };

        // Check for non-existent column names
        for col in id_vars.iter().chain(value_vars.iter()) {
            if !self.column_indices.contains_key(*col) {
                return Err(Error::ColumnNotFound((*col).to_string()));
            }
        }

        // Precompute the size of the result (performance optimization)
        let result_rows = self.row_count * value_vars.len();

        // Extract data for ID columns
        let mut id_columns = Vec::with_capacity(id_vars.len());
        for &id_col in id_vars {
            let idx = self.column_indices[id_col];
            id_columns.push((id_col, &self.columns[idx]));
        }

        // Extract data for value columns
        let mut value_columns = Vec::with_capacity(value_vars.len());
        for &val_col in &value_vars {
            let idx = self.column_indices[val_col];
            value_columns.push((val_col, &self.columns[idx]));
        }

        // Create the result DataFrame
        let mut result = Self::new();

        // Create the variable name column
        let mut var_col_data = Vec::with_capacity(result_rows);
        for &value_col_name in &value_vars {
            for _ in 0..self.row_count {
                var_col_data.push(value_col_name.to_string());
            }
        }
        result.add_column(
            var_name.to_string(),
            Column::String(StringColumn::new(var_col_data)),
        )?;

        // Replicate and add ID columns
        for &(id_col_name, col) in &id_columns {
            match col {
                Column::Int64(int_col) => {
                    // Integer column
                    let mut repeated_data = Vec::with_capacity(result_rows);
                    for _ in 0..value_vars.len() {
                        for i in 0..self.row_count {
                            if let Ok(Some(val)) = int_col.get(i) {
                                repeated_data.push(val);
                            } else {
                                // Use default value for NULLs
                                repeated_data.push(0);
                            }
                        }
                    }
                    result.add_column(
                        id_col_name.to_string(),
                        Column::Int64(Int64Column::new(repeated_data)),
                    )?;
                }
                Column::Float64(float_col) => {
                    // Float column
                    let mut repeated_data = Vec::with_capacity(result_rows);
                    for _ in 0..value_vars.len() {
                        for i in 0..self.row_count {
                            if let Ok(Some(val)) = float_col.get(i) {
                                repeated_data.push(val);
                            } else {
                                // Use default value for NULLs
                                repeated_data.push(0.0);
                            }
                        }
                    }
                    result.add_column(
                        id_col_name.to_string(),
                        Column::Float64(Float64Column::new(repeated_data)),
                    )?;
                }
                Column::String(str_col) => {
                    // String column
                    let mut repeated_data = Vec::with_capacity(result_rows);
                    for _ in 0..value_vars.len() {
                        for i in 0..self.row_count {
                            if let Ok(Some(val)) = str_col.get(i) {
                                repeated_data.push(val.to_string());
                            } else {
                                // Use default value for NULLs
                                repeated_data.push(String::new());
                            }
                        }
                    }
                    result.add_column(
                        id_col_name.to_string(),
                        Column::String(StringColumn::new(repeated_data)),
                    )?;
                }
                Column::Boolean(bool_col) => {
                    // Boolean column
                    let mut repeated_data = Vec::with_capacity(result_rows);
                    for _ in 0..value_vars.len() {
                        for i in 0..self.row_count {
                            if let Ok(Some(val)) = bool_col.get(i) {
                                repeated_data.push(val);
                            } else {
                                // Use default value for NULLs
                                repeated_data.push(false);
                            }
                        }
                    }
                    result.add_column(
                        id_col_name.to_string(),
                        Column::Boolean(BooleanColumn::new(repeated_data)),
                    )?;
                }
            }
        }

        // Create value columns (optimized for each type)
        // To optimize, collect all values as strings first
        let mut all_values = Vec::with_capacity(result_rows);

        for (_, col) in value_columns {
            match col {
                Column::Int64(int_col) => {
                    for i in 0..self.row_count {
                        if let Ok(Some(val)) = int_col.get(i) {
                            all_values.push(val.to_string());
                        } else {
                            all_values.push(String::new());
                        }
                    }
                }
                Column::Float64(float_col) => {
                    for i in 0..self.row_count {
                        if let Ok(Some(val)) = float_col.get(i) {
                            all_values.push(val.to_string());
                        } else {
                            all_values.push(String::new());
                        }
                    }
                }
                Column::String(str_col) => {
                    for i in 0..self.row_count {
                        if let Ok(Some(val)) = str_col.get(i) {
                            all_values.push(val.to_string());
                        } else {
                            all_values.push(String::new());
                        }
                    }
                }
                Column::Boolean(bool_col) => {
                    for i in 0..self.row_count {
                        if let Ok(Some(val)) = bool_col.get(i) {
                            all_values.push(val.to_string());
                        } else {
                            all_values.push(String::new());
                        }
                    }
                }
            }
        }

        // Determine the appropriate type and add data
        let is_all_int = all_values
            .iter()
            .all(|s| s.parse::<i64>().is_ok() || s.is_empty());

        let is_all_float = !is_all_int
            && all_values
                .iter()
                .all(|s| s.parse::<f64>().is_ok() || s.is_empty());

        let is_all_bool = !is_all_int
            && !is_all_float
            && all_values.iter().all(|s| {
                let lower = s.to_lowercase();
                lower.is_empty()
                    || lower == "true"
                    || lower == "false"
                    || lower == "1"
                    || lower == "0"
                    || lower == "yes"
                    || lower == "no"
            });

        // Add columns based on the determined type
        if is_all_int {
            let int_values: Vec<i64> = all_values
                .iter()
                .map(|s| s.parse::<i64>().unwrap_or(0))
                .collect();
            result.add_column(
                value_name.to_string(),
                Column::Int64(Int64Column::new(int_values)),
            )?;
        } else if is_all_float {
            let float_values: Vec<f64> = all_values
                .iter()
                .map(|s| s.parse::<f64>().unwrap_or(0.0))
                .collect();
            result.add_column(
                value_name.to_string(),
                Column::Float64(Float64Column::new(float_values)),
            )?;
        } else if is_all_bool {
            let bool_values: Vec<bool> = all_values
                .iter()
                .map(|s| {
                    let lower = s.to_lowercase();
                    lower == "true" || lower == "1" || lower == "yes"
                })
                .collect();
            result.add_column(
                value_name.to_string(),
                Column::Boolean(BooleanColumn::new(bool_values)),
            )?;
        } else {
            // Default to string type
            result.add_column(
                value_name.to_string(),
                Column::String(StringColumn::new(all_values)),
            )?;
        }

        Ok(result)
    }

    /// Concatenate DataFrames vertically
    ///
    /// # Arguments
    /// * `other` - DataFrame to concatenate
    ///
    /// # Returns
    /// * `Result<Self>` - Concatenated DataFrame
    pub fn append(&self, other: &Self) -> Result<Self> {
        if self.columns.is_empty() {
            return Ok(other.clone());
        }

        if other.columns.is_empty() {
            return Ok(self.clone());
        }

        // Create the result DataFrame
        let mut result = Self::new();

        // Create a set of all column names
        let mut all_columns = std::collections::HashSet::new();

        for name in &self.column_names {
            all_columns.insert(name.clone());
        }

        for name in &other.column_names {
            all_columns.insert(name.clone());
        }

        // Prepare new column data
        for col_name in all_columns {
            let self_has_column = self.column_indices.contains_key(&col_name);
            let other_has_column = other.column_indices.contains_key(&col_name);

            // If both DataFrames have the column
            if self_has_column && other_has_column {
                let self_col_idx = self.column_indices[&col_name];
                let other_col_idx = other.column_indices[&col_name];

                let self_col = &self.columns[self_col_idx];
                let other_col = &other.columns[other_col_idx];

                // Concatenate columns of the same type
                if self_col.column_type() == other_col.column_type() {
                    match (self_col, other_col) {
                        (Column::Int64(self_int), Column::Int64(other_int)) => {
                            let mut combined_data =
                                Vec::with_capacity(self_int.len() + other_int.len());

                            // Add self data
                            for i in 0..self_int.len() {
                                if let Ok(Some(val)) = self_int.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(0); // Default value
                                }
                            }

                            // Add other data
                            for i in 0..other_int.len() {
                                if let Ok(Some(val)) = other_int.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(0); // Default value
                                }
                            }

                            result.add_column(
                                col_name,
                                Column::Int64(Int64Column::new(combined_data)),
                            )?;
                        }
                        (Column::Float64(self_float), Column::Float64(other_float)) => {
                            let mut combined_data =
                                Vec::with_capacity(self_float.len() + other_float.len());

                            // Add self data
                            for i in 0..self_float.len() {
                                if let Ok(Some(val)) = self_float.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(0.0); // Default value
                                }
                            }

                            // Add other data
                            for i in 0..other_float.len() {
                                if let Ok(Some(val)) = other_float.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(0.0); // Default value
                                }
                            }

                            result.add_column(
                                col_name,
                                Column::Float64(Float64Column::new(combined_data)),
                            )?;
                        }
                        (Column::String(self_str), Column::String(other_str)) => {
                            let mut combined_data =
                                Vec::with_capacity(self_str.len() + other_str.len());

                            // Add self data
                            for i in 0..self_str.len() {
                                if let Ok(Some(val)) = self_str.get(i) {
                                    combined_data.push(val.to_string());
                                } else {
                                    combined_data.push(String::new()); // Default value
                                }
                            }

                            // Add other data
                            for i in 0..other_str.len() {
                                if let Ok(Some(val)) = other_str.get(i) {
                                    combined_data.push(val.to_string());
                                } else {
                                    combined_data.push(String::new()); // Default value
                                }
                            }

                            result.add_column(
                                col_name,
                                Column::String(StringColumn::new(combined_data)),
                            )?;
                        }
                        (Column::Boolean(self_bool), Column::Boolean(other_bool)) => {
                            let mut combined_data =
                                Vec::with_capacity(self_bool.len() + other_bool.len());

                            // Add self data
                            for i in 0..self_bool.len() {
                                if let Ok(Some(val)) = self_bool.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(false); // Default value
                                }
                            }

                            // Add other data
                            for i in 0..other_bool.len() {
                                if let Ok(Some(val)) = other_bool.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(false); // Default value
                                }
                            }

                            result.add_column(
                                col_name,
                                Column::Boolean(BooleanColumn::new(combined_data)),
                            )?;
                        }
                        _ => {
                            // Concatenate as strings if types do not match
                            let mut combined_data =
                                Vec::with_capacity(self.row_count + other.row_count);

                            // Add self data
                            for i in 0..self.row_count {
                                let value = match self_col {
                                    Column::Int64(col) => col
                                        .get(i)
                                        .ok()
                                        .flatten()
                                        .map(|v| v.to_string())
                                        .unwrap_or_default(),
                                    Column::Float64(col) => col
                                        .get(i)
                                        .ok()
                                        .flatten()
                                        .map(|v| v.to_string())
                                        .unwrap_or_default(),
                                    Column::String(col) => col
                                        .get(i)
                                        .ok()
                                        .flatten()
                                        .map(|v| v.to_string())
                                        .unwrap_or_default(),
                                    Column::Boolean(col) => col
                                        .get(i)
                                        .ok()
                                        .flatten()
                                        .map(|v| v.to_string())
                                        .unwrap_or_default(),
                                };
                                combined_data.push(value);
                            }

                            // Add other data
                            for i in 0..other.row_count {
                                let value = match other_col {
                                    Column::Int64(col) => col
                                        .get(i)
                                        .ok()
                                        .flatten()
                                        .map(|v| v.to_string())
                                        .unwrap_or_default(),
                                    Column::Float64(col) => col
                                        .get(i)
                                        .ok()
                                        .flatten()
                                        .map(|v| v.to_string())
                                        .unwrap_or_default(),
                                    Column::String(col) => col
                                        .get(i)
                                        .ok()
                                        .flatten()
                                        .map(|v| v.to_string())
                                        .unwrap_or_default(),
                                    Column::Boolean(col) => col
                                        .get(i)
                                        .ok()
                                        .flatten()
                                        .map(|v| v.to_string())
                                        .unwrap_or_default(),
                                };
                                combined_data.push(value);
                            }

                            result.add_column(
                                col_name,
                                Column::String(StringColumn::new(combined_data)),
                            )?;
                        }
                    }
                }
                // Concatenate as strings if types do not match
                else {
                    let mut combined_data = Vec::with_capacity(self.row_count + other.row_count);

                    // Add self data
                    for i in 0..self.row_count {
                        let value = match self_col {
                            Column::Int64(col) => col
                                .get(i)
                                .ok()
                                .flatten()
                                .map(|v| v.to_string())
                                .unwrap_or_default(),
                            Column::Float64(col) => col
                                .get(i)
                                .ok()
                                .flatten()
                                .map(|v| v.to_string())
                                .unwrap_or_default(),
                            Column::String(col) => col
                                .get(i)
                                .ok()
                                .flatten()
                                .map(|v| v.to_string())
                                .unwrap_or_default(),
                            Column::Boolean(col) => col
                                .get(i)
                                .ok()
                                .flatten()
                                .map(|v| v.to_string())
                                .unwrap_or_default(),
                        };
                        combined_data.push(value);
                    }

                    // Add other data
                    for i in 0..other.row_count {
                        let value = match other_col {
                            Column::Int64(col) => col
                                .get(i)
                                .ok()
                                .flatten()
                                .map(|v| v.to_string())
                                .unwrap_or_default(),
                            Column::Float64(col) => col
                                .get(i)
                                .ok()
                                .flatten()
                                .map(|v| v.to_string())
                                .unwrap_or_default(),
                            Column::String(col) => col
                                .get(i)
                                .ok()
                                .flatten()
                                .map(|v| v.to_string())
                                .unwrap_or_default(),
                            Column::Boolean(col) => col
                                .get(i)
                                .ok()
                                .flatten()
                                .map(|v| v.to_string())
                                .unwrap_or_default(),
                        };
                        combined_data.push(value);
                    }

                    result
                        .add_column(col_name, Column::String(StringColumn::new(combined_data)))?;
                }
            }
            // If the column exists in only one DataFrame
            else {
                let total_rows = self.row_count + other.row_count;

                if self_has_column {
                    let col_idx = self.column_indices[&col_name];
                    let column = &self.columns[col_idx];

                    match column {
                        Column::Int64(int_col) => {
                            let mut combined_data = Vec::with_capacity(total_rows);

                            // Add self data
                            for i in 0..int_col.len() {
                                if let Ok(Some(val)) = int_col.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(0); // Default value
                                }
                            }

                            // Fill missing data with default values
                            combined_data.resize(total_rows, 0);

                            result.add_column(
                                col_name,
                                Column::Int64(Int64Column::new(combined_data)),
                            )?;
                        }
                        Column::Float64(float_col) => {
                            let mut combined_data = Vec::with_capacity(total_rows);

                            // Add self data
                            for i in 0..float_col.len() {
                                if let Ok(Some(val)) = float_col.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(0.0); // Default value
                                }
                            }

                            // Fill missing data with default values
                            combined_data.resize(total_rows, 0.0);

                            result.add_column(
                                col_name,
                                Column::Float64(Float64Column::new(combined_data)),
                            )?;
                        }
                        Column::String(str_col) => {
                            let mut combined_data = Vec::with_capacity(total_rows);

                            // Add self data
                            for i in 0..str_col.len() {
                                if let Ok(Some(val)) = str_col.get(i) {
                                    combined_data.push(val.to_string());
                                } else {
                                    combined_data.push(String::new()); // Default value
                                }
                            }

                            // Fill missing data with default values
                            combined_data.resize(total_rows, String::new());

                            result.add_column(
                                col_name,
                                Column::String(StringColumn::new(combined_data)),
                            )?;
                        }
                        Column::Boolean(bool_col) => {
                            let mut combined_data = Vec::with_capacity(total_rows);

                            // Add self data
                            for i in 0..bool_col.len() {
                                if let Ok(Some(val)) = bool_col.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(false); // Default value
                                }
                            }

                            // Fill missing data with default values
                            combined_data.resize(total_rows, false);

                            result.add_column(
                                col_name,
                                Column::Boolean(BooleanColumn::new(combined_data)),
                            )?;
                        }
                    }
                } else if other_has_column {
                    let col_idx = other.column_indices[&col_name];
                    let column = &other.columns[col_idx];

                    match column {
                        Column::Int64(int_col) => {
                            let mut combined_data = Vec::with_capacity(total_rows);

                            // Fill missing data with default values
                            combined_data.resize(self.row_count, 0);

                            // Add other data
                            for i in 0..int_col.len() {
                                if let Ok(Some(val)) = int_col.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(0); // Default value
                                }
                            }

                            result.add_column(
                                col_name,
                                Column::Int64(Int64Column::new(combined_data)),
                            )?;
                        }
                        Column::Float64(float_col) => {
                            let mut combined_data = Vec::with_capacity(total_rows);

                            // Fill missing data with default values
                            combined_data.resize(self.row_count, 0.0);

                            // Add other data
                            for i in 0..float_col.len() {
                                if let Ok(Some(val)) = float_col.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(0.0); // Default value
                                }
                            }

                            result.add_column(
                                col_name,
                                Column::Float64(Float64Column::new(combined_data)),
                            )?;
                        }
                        Column::String(str_col) => {
                            let mut combined_data = Vec::with_capacity(total_rows);

                            // Fill missing data with default values
                            combined_data.resize(self.row_count, String::new());

                            // Add other data
                            for i in 0..str_col.len() {
                                if let Ok(Some(val)) = str_col.get(i) {
                                    combined_data.push(val.to_string());
                                } else {
                                    combined_data.push(String::new()); // Default value
                                }
                            }

                            result.add_column(
                                col_name,
                                Column::String(StringColumn::new(combined_data)),
                            )?;
                        }
                        Column::Boolean(bool_col) => {
                            let mut combined_data = Vec::with_capacity(total_rows);

                            // Fill missing data with default values
                            combined_data.resize(self.row_count, false);

                            // Add other data
                            for i in 0..bool_col.len() {
                                if let Ok(Some(val)) = bool_col.get(i) {
                                    combined_data.push(val);
                                } else {
                                    combined_data.push(false); // Default value
                                }
                            }

                            result.add_column(
                                col_name,
                                Column::Boolean(BooleanColumn::new(combined_data)),
                            )?;
                        }
                    }
                }
            }
        }

        Ok(result)
    }
}