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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
//! Advanced specialized indexing types for DataFrames
//!
//! This module provides specialized index types for specific use cases:
//! - DatetimeIndex: Time series indexing with timezone support
//! - PeriodIndex: Business period indexing (quarters, months, etc.)
//! - IntervalIndex: Range-based and binned data indexing  
//! - CategoricalIndex: Memory-optimized categorical indexing
//! - Index set operations: union, intersection, difference, symmetric_difference

use std::collections::{HashMap, HashSet};
use std::fmt;

use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, NaiveDateTime, Timelike, Utc};
use chrono_tz::Tz;

use crate::core::error::{Error, Result};
use crate::dataframe::base::DataFrame;
use crate::dataframe::indexing::AdvancedIndexingExt as DataFrameIndexingExt;
use crate::series::base::Series;

/// Trait for all index types
pub trait Index: fmt::Debug + Clone {
    /// Get the length of the index
    fn len(&self) -> usize;

    /// Check if the index is empty
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get string representation of index values
    fn to_string_vec(&self) -> Vec<String>;

    /// Get the name of the index
    fn name(&self) -> Option<&str>;

    /// Set the name of the index
    fn set_name(&mut self, name: Option<String>);

    /// Check if index contains duplicates
    fn has_duplicates(&self) -> bool;

    /// Get unique values (returns same type)
    fn unique(&self) -> Result<Self>
    where
        Self: Sized;

    /// Sort the index (returns same type)
    fn sort(&self, ascending: bool) -> Result<(Self, Vec<usize>)>
    where
        Self: Sized;
}

/// Enum wrapper for different index types (for polymorphic usage)
#[derive(Debug, Clone)]
pub enum IndexType {
    Datetime(DatetimeIndex),
    Period(PeriodIndex),
    Interval(IntervalIndex),
    Categorical(CategoricalIndex),
}

impl IndexType {
    /// Get the length of the index
    pub fn len(&self) -> usize {
        match self {
            IndexType::Datetime(idx) => idx.len(),
            IndexType::Period(idx) => idx.len(),
            IndexType::Interval(idx) => idx.len(),
            IndexType::Categorical(idx) => idx.len(),
        }
    }

    /// Check if the index is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get string representation of index values
    pub fn to_string_vec(&self) -> Vec<String> {
        match self {
            IndexType::Datetime(idx) => idx.to_string_vec(),
            IndexType::Period(idx) => idx.to_string_vec(),
            IndexType::Interval(idx) => idx.to_string_vec(),
            IndexType::Categorical(idx) => idx.to_string_vec(),
        }
    }

    /// Get the name of the index
    pub fn name(&self) -> Option<&str> {
        match self {
            IndexType::Datetime(idx) => idx.name(),
            IndexType::Period(idx) => idx.name(),
            IndexType::Interval(idx) => idx.name(),
            IndexType::Categorical(idx) => idx.name(),
        }
    }

    /// Check if index contains duplicates
    pub fn has_duplicates(&self) -> bool {
        match self {
            IndexType::Datetime(idx) => idx.has_duplicates(),
            IndexType::Period(idx) => idx.has_duplicates(),
            IndexType::Interval(idx) => idx.has_duplicates(),
            IndexType::Categorical(idx) => idx.has_duplicates(),
        }
    }
}

/// Index set operations trait
pub trait IndexSetOps<T: Index> {
    /// Union of two indexes
    fn union(&self, other: &T) -> Result<IndexType>;

    /// Intersection of two indexes
    fn intersection(&self, other: &T) -> Result<IndexType>;

    /// Difference of two indexes (self - other)
    fn difference(&self, other: &T) -> Result<IndexType>;

    /// Symmetric difference of two indexes
    fn symmetric_difference(&self, other: &T) -> Result<IndexType>;
}

/// DateTime index for time series data
#[derive(Debug, Clone)]
pub struct DatetimeIndex {
    /// DateTime values
    pub values: Vec<NaiveDateTime>,
    /// Index name
    pub name: Option<String>,
    /// Timezone information (optional)
    pub timezone: Option<Tz>,
    /// Frequency information (optional)
    pub frequency: Option<String>,
}

impl DatetimeIndex {
    /// Create a new datetime index
    pub fn new(values: Vec<NaiveDateTime>, name: Option<String>) -> Self {
        Self {
            values,
            name,
            timezone: None,
            frequency: None,
        }
    }

    /// Create a datetime index with timezone
    pub fn with_timezone(values: Vec<NaiveDateTime>, name: Option<String>, timezone: Tz) -> Self {
        Self {
            values,
            name,
            timezone: Some(timezone),
            frequency: None,
        }
    }

    /// Create a datetime range with frequency
    pub fn date_range(
        start: NaiveDateTime,
        end: Option<NaiveDateTime>,
        periods: Option<usize>,
        frequency: &str,
        name: Option<String>,
    ) -> Result<Self> {
        let freq_duration = Self::parse_frequency(frequency)?;
        let mut values = Vec::new();

        match (end, periods) {
            (Some(end_date), None) => {
                // Generate range from start to end
                let mut current = start;
                while current <= end_date {
                    values.push(current);
                    current = current + freq_duration;
                }
            }
            (None, Some(periods_count)) => {
                // Generate specific number of periods
                let mut current = start;
                for _ in 0..periods_count {
                    values.push(current);
                    current = current + freq_duration;
                }
            }
            (Some(end_date), Some(periods_count)) => {
                // Use periods count, ignore end date
                let mut current = start;
                for _ in 0..periods_count {
                    values.push(current);
                    current = current + freq_duration;
                    if current > end_date {
                        break;
                    }
                }
            }
            (None, None) => {
                return Err(Error::InvalidValue(
                    "Either end date or periods must be specified".to_string(),
                ));
            }
        }

        Ok(Self {
            values,
            name,
            timezone: None,
            frequency: Some(frequency.to_string()),
        })
    }

    /// Parse frequency string to Duration
    fn parse_frequency(freq: &str) -> Result<Duration> {
        let freq = freq.to_lowercase();
        match freq.as_str() {
            "d" | "day" | "days" => Ok(Duration::days(1)),
            "h" | "hour" | "hours" => Ok(Duration::hours(1)),
            "min" | "minute" | "minutes" => Ok(Duration::minutes(1)),
            "s" | "second" | "seconds" => Ok(Duration::seconds(1)),
            "w" | "week" | "weeks" => Ok(Duration::weeks(1)),
            "ms" | "millisecond" | "milliseconds" => Ok(Duration::milliseconds(1)),
            _ => {
                // Simple numeric frequency parsing for common patterns
                if freq.ends_with("min") || freq.ends_with("minutes") {
                    let num_str = freq.trim_end_matches("min").trim_end_matches("utes");
                    if let Ok(num) = num_str.parse::<i64>() {
                        Ok(Duration::minutes(num))
                    } else {
                        Err(Error::InvalidValue(format!(
                            "Invalid frequency format: {}",
                            freq
                        )))
                    }
                } else if freq.ends_with("h") || freq.ends_with("hour") || freq.ends_with("hours") {
                    let num_str = freq
                        .trim_end_matches("h")
                        .trim_end_matches("our")
                        .trim_end_matches("s");
                    if let Ok(num) = num_str.parse::<i64>() {
                        Ok(Duration::hours(num))
                    } else {
                        Err(Error::InvalidValue(format!(
                            "Invalid frequency format: {}",
                            freq
                        )))
                    }
                } else if freq.ends_with("d") || freq.ends_with("day") || freq.ends_with("days") {
                    let num_str = freq
                        .trim_end_matches("d")
                        .trim_end_matches("ay")
                        .trim_end_matches("s");
                    if let Ok(num) = num_str.parse::<i64>() {
                        Ok(Duration::days(num))
                    } else {
                        Err(Error::InvalidValue(format!(
                            "Invalid frequency format: {}",
                            freq
                        )))
                    }
                } else {
                    Err(Error::InvalidValue(format!(
                        "Invalid frequency format: {}",
                        freq
                    )))
                }
            }
        }
    }

    /// Get year component
    pub fn year(&self) -> Vec<i32> {
        self.values.iter().map(|dt| dt.year()).collect()
    }

    /// Get month component
    pub fn month(&self) -> Vec<u32> {
        self.values.iter().map(|dt| dt.month()).collect()
    }

    /// Get day component
    pub fn day(&self) -> Vec<u32> {
        self.values.iter().map(|dt| dt.day()).collect()
    }

    /// Get hour component
    pub fn hour(&self) -> Vec<u32> {
        self.values.iter().map(|dt| dt.hour()).collect()
    }

    /// Get minute component
    pub fn minute(&self) -> Vec<u32> {
        self.values.iter().map(|dt| dt.minute()).collect()
    }

    /// Get weekday component (0=Monday, 6=Sunday)
    pub fn weekday(&self) -> Vec<u32> {
        self.values
            .iter()
            .map(|dt| dt.weekday().num_days_from_monday())
            .collect()
    }

    /// Filter by date range
    pub fn filter_range(&self, start: NaiveDateTime, end: NaiveDateTime) -> Result<Vec<usize>> {
        Ok(self
            .values
            .iter()
            .enumerate()
            .filter_map(|(i, dt)| {
                if *dt >= start && *dt <= end {
                    Some(i)
                } else {
                    None
                }
            })
            .collect())
    }

    /// Resample to different frequency
    pub fn resample(&self, frequency: &str) -> Result<Vec<Vec<usize>>> {
        let freq_duration = Self::parse_frequency(frequency)?;
        let mut groups = Vec::new();

        if self.values.is_empty() {
            return Ok(groups);
        }

        let mut current_group = Vec::new();
        let mut group_start = self.values[0];

        for (i, dt) in self.values.iter().enumerate() {
            if *dt >= group_start + freq_duration {
                if !current_group.is_empty() {
                    groups.push(current_group);
                    current_group = Vec::new();
                }
                group_start = *dt;
            }
            current_group.push(i);
        }

        if !current_group.is_empty() {
            groups.push(current_group);
        }

        Ok(groups)
    }
}

impl Index for DatetimeIndex {
    fn len(&self) -> usize {
        self.values.len()
    }

    fn to_string_vec(&self) -> Vec<String> {
        self.values
            .iter()
            .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
            .collect()
    }

    fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    fn set_name(&mut self, name: Option<String>) {
        self.name = name;
    }

    fn has_duplicates(&self) -> bool {
        let mut seen = HashSet::new();
        self.values.iter().any(|dt| !seen.insert(dt))
    }

    fn unique(&self) -> Result<Self> {
        let mut unique_values: Vec<NaiveDateTime> = self.values.clone();
        unique_values.sort();
        unique_values.dedup();

        Ok(DatetimeIndex::new(unique_values, self.name.clone()))
    }

    fn sort(&self, ascending: bool) -> Result<(Self, Vec<usize>)> {
        let mut indices: Vec<usize> = (0..self.values.len()).collect();

        if ascending {
            indices.sort_by(|&a, &b| self.values[a].cmp(&self.values[b]));
        } else {
            indices.sort_by(|&a, &b| self.values[b].cmp(&self.values[a]));
        }

        let sorted_values: Vec<NaiveDateTime> = indices.iter().map(|&i| self.values[i]).collect();
        let sorted_index = DatetimeIndex::new(sorted_values, self.name.clone());

        Ok((sorted_index, indices))
    }
}

/// Period index for business periods (quarters, months, etc.)
#[derive(Debug, Clone)]
pub struct PeriodIndex {
    /// Period values
    pub periods: Vec<Period>,
    /// Index name
    pub name: Option<String>,
    /// Frequency of periods
    pub frequency: PeriodFrequency,
}

/// Period frequency enumeration
#[derive(Debug, Clone, PartialEq)]
pub enum PeriodFrequency {
    /// Annual periods
    Annual,
    /// Quarterly periods  
    Quarterly,
    /// Monthly periods
    Monthly,
    /// Weekly periods
    Weekly,
    /// Daily periods
    Daily,
}

/// Individual period representation
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Period {
    /// Period start date
    pub start: NaiveDate,
    /// Period end date
    pub end: NaiveDate,
    /// Period label (e.g., "2024-Q1", "2024-03")
    pub label: String,
}

impl Period {
    /// Create a new period
    pub fn new(start: NaiveDate, end: NaiveDate, label: String) -> Self {
        Self { start, end, label }
    }

    /// Check if a date falls within this period
    pub fn contains(&self, date: NaiveDate) -> bool {
        date >= self.start && date <= self.end
    }

    /// Get period duration in days
    pub fn duration_days(&self) -> i64 {
        (self.end - self.start).num_days() + 1
    }
}

impl PeriodIndex {
    /// Create a new period index
    pub fn new(periods: Vec<Period>, frequency: PeriodFrequency, name: Option<String>) -> Self {
        Self {
            periods,
            name,
            frequency,
        }
    }

    /// Create period range
    pub fn period_range(
        start: NaiveDate,
        end: NaiveDate,
        frequency: PeriodFrequency,
        name: Option<String>,
    ) -> Result<Self> {
        let mut periods = Vec::new();
        let mut current = start;

        while current <= end {
            let (period_end, label) = match frequency {
                PeriodFrequency::Annual => {
                    let year = current.year();
                    let period_start = NaiveDate::from_ymd_opt(year, 1, 1)
                        .ok_or_else(|| Error::InvalidValue("Invalid year".to_string()))?;
                    let period_end = NaiveDate::from_ymd_opt(year, 12, 31)
                        .ok_or_else(|| Error::InvalidValue("Invalid year".to_string()))?;
                    (period_end, format!("{}", year))
                }
                PeriodFrequency::Quarterly => {
                    let year = current.year();
                    let quarter = ((current.month() - 1) / 3) + 1;
                    let quarter_start_month = ((quarter - 1) * 3) + 1;
                    let quarter_end_month = quarter * 3;

                    let period_end = NaiveDate::from_ymd_opt(
                        year,
                        quarter_end_month,
                        match quarter_end_month {
                            3 => 31,
                            6 => 30,
                            9 => 30,
                            12 => 31,
                            _ => return Err(Error::InvalidValue("Invalid quarter".to_string())),
                        },
                    )
                    .ok_or_else(|| Error::InvalidValue("Invalid quarter end date".to_string()))?;

                    (period_end, format!("{}-Q{}", year, quarter))
                }
                PeriodFrequency::Monthly => {
                    let year = current.year();
                    let month = current.month();

                    // Get last day of month
                    let next_month = if month == 12 { 1 } else { month + 1 };
                    let next_year = if month == 12 { year + 1 } else { year };
                    let first_of_next = NaiveDate::from_ymd_opt(next_year, next_month, 1)
                        .ok_or_else(|| Error::InvalidValue("Invalid next month".to_string()))?;
                    let period_end = first_of_next
                        .pred_opt()
                        .ok_or_else(|| Error::InvalidValue("Invalid month end".to_string()))?;

                    (period_end, format!("{}-{:02}", year, month))
                }
                PeriodFrequency::Weekly => {
                    let period_end = current + Duration::days(6);
                    (
                        period_end.min(end),
                        format!("{}-W{:02}", current.year(), current.iso_week().week()),
                    )
                }
                PeriodFrequency::Daily => (current, current.format("%Y-%m-%d").to_string()),
            };

            periods.push(Period::new(current, period_end, label));

            // Move to next period
            current = match frequency {
                PeriodFrequency::Annual => NaiveDate::from_ymd_opt(current.year() + 1, 1, 1)
                    .ok_or_else(|| Error::InvalidValue("Invalid next year".to_string()))?,
                PeriodFrequency::Quarterly => {
                    let quarter = ((current.month() - 1) / 3) + 1;
                    if quarter == 4 {
                        NaiveDate::from_ymd_opt(current.year() + 1, 1, 1)
                    } else {
                        NaiveDate::from_ymd_opt(current.year(), ((quarter) * 3) + 1, 1)
                    }
                    .ok_or_else(|| Error::InvalidValue("Invalid next quarter".to_string()))?
                }
                PeriodFrequency::Monthly => if current.month() == 12 {
                    NaiveDate::from_ymd_opt(current.year() + 1, 1, 1)
                } else {
                    NaiveDate::from_ymd_opt(current.year(), current.month() + 1, 1)
                }
                .ok_or_else(|| Error::InvalidValue("Invalid next month".to_string()))?,
                PeriodFrequency::Weekly => current + Duration::days(7),
                PeriodFrequency::Daily => current + Duration::days(1),
            };

            if current > end {
                break;
            }
        }

        Ok(Self::new(periods, frequency, name))
    }

    /// Find periods containing a specific date
    pub fn find_periods_containing(&self, date: NaiveDate) -> Vec<usize> {
        self.periods
            .iter()
            .enumerate()
            .filter_map(
                |(i, period)| {
                    if period.contains(date) {
                        Some(i)
                    } else {
                        None
                    }
                },
            )
            .collect()
    }

    /// Get period labels
    pub fn labels(&self) -> Vec<&str> {
        self.periods.iter().map(|p| p.label.as_str()).collect()
    }
}

impl Index for PeriodIndex {
    fn len(&self) -> usize {
        self.periods.len()
    }

    fn to_string_vec(&self) -> Vec<String> {
        self.periods.iter().map(|p| p.label.clone()).collect()
    }

    fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    fn set_name(&mut self, name: Option<String>) {
        self.name = name;
    }

    fn has_duplicates(&self) -> bool {
        let mut seen = HashSet::new();
        self.periods.iter().any(|p| !seen.insert(&p.label))
    }

    fn unique(&self) -> Result<Self> {
        let mut unique_periods: Vec<Period> = self.periods.clone();
        unique_periods.sort_by(|a, b| a.label.cmp(&b.label));
        unique_periods.dedup_by(|a, b| a.label == b.label);

        Ok(PeriodIndex::new(
            unique_periods,
            self.frequency.clone(),
            self.name.clone(),
        ))
    }

    fn sort(&self, ascending: bool) -> Result<(Self, Vec<usize>)> {
        let mut indices: Vec<usize> = (0..self.periods.len()).collect();

        if ascending {
            indices.sort_by(|&a, &b| self.periods[a].start.cmp(&self.periods[b].start));
        } else {
            indices.sort_by(|&a, &b| self.periods[b].start.cmp(&self.periods[a].start));
        }

        let sorted_periods: Vec<Period> =
            indices.iter().map(|&i| self.periods[i].clone()).collect();
        let sorted_index =
            PeriodIndex::new(sorted_periods, self.frequency.clone(), self.name.clone());

        Ok((sorted_index, indices))
    }
}

/// Interval index for range-based and binned data indexing
#[derive(Debug, Clone)]
pub struct IntervalIndex {
    /// Interval values
    pub intervals: Vec<Interval>,
    /// Index name
    pub name: Option<String>,
    /// Whether intervals are closed on left, right, both, or neither
    pub closed: IntervalClosed,
}

/// Interval closed specification
#[derive(Debug, Clone, PartialEq)]
pub enum IntervalClosed {
    /// Intervals are closed on the left: [a, b)
    Left,
    /// Intervals are closed on the right: (a, b]
    Right,
    /// Intervals are closed on both sides: [a, b]
    Both,
    /// Intervals are open on both sides: (a, b)
    Neither,
}

/// Individual interval representation
#[derive(Debug, Clone, PartialEq)]
pub struct Interval {
    /// Left boundary
    pub left: f64,
    /// Right boundary
    pub right: f64,
    /// Interval label
    pub label: String,
}

impl Interval {
    /// Create a new interval
    pub fn new(left: f64, right: f64) -> Self {
        let label = format!("({}, {})", left, right);
        Self { left, right, label }
    }

    /// Create interval with custom label
    pub fn with_label(left: f64, right: f64, label: String) -> Self {
        Self { left, right, label }
    }

    /// Check if a value falls within this interval
    pub fn contains(&self, value: f64, closed: &IntervalClosed) -> bool {
        match closed {
            IntervalClosed::Left => value >= self.left && value < self.right,
            IntervalClosed::Right => value > self.left && value <= self.right,
            IntervalClosed::Both => value >= self.left && value <= self.right,
            IntervalClosed::Neither => value > self.left && value < self.right,
        }
    }

    /// Get interval width
    pub fn width(&self) -> f64 {
        self.right - self.left
    }

    /// Get interval midpoint
    pub fn midpoint(&self) -> f64 {
        (self.left + self.right) / 2.0
    }
}

impl IntervalIndex {
    /// Create a new interval index
    pub fn new(intervals: Vec<Interval>, closed: IntervalClosed, name: Option<String>) -> Self {
        Self {
            intervals,
            name,
            closed,
        }
    }

    /// Create interval index from breaks
    pub fn from_breaks(
        breaks: Vec<f64>,
        closed: IntervalClosed,
        name: Option<String>,
    ) -> Result<Self> {
        if breaks.len() < 2 {
            return Err(Error::InvalidValue(
                "At least 2 breaks required".to_string(),
            ));
        }

        let mut sorted_breaks = breaks;
        sorted_breaks.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let intervals: Vec<Interval> = sorted_breaks
            .windows(2)
            .map(|window| Interval::new(window[0], window[1]))
            .collect();

        Ok(Self::new(intervals, closed, name))
    }

    /// Create equal-width bins
    pub fn cut(
        values: &[f64],
        bins: usize,
        closed: IntervalClosed,
        name: Option<String>,
    ) -> Result<Self> {
        if values.is_empty() {
            return Err(Error::InvalidValue("Cannot cut empty values".to_string()));
        }

        let min_val = values.iter().fold(f64::INFINITY, |a, &b| a.min(b));
        let max_val = values.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));

        if min_val == max_val {
            return Err(Error::InvalidValue("All values are identical".to_string()));
        }

        let width = (max_val - min_val) / bins as f64;
        let mut breaks = Vec::with_capacity(bins + 1);

        for i in 0..=bins {
            breaks.push(min_val + (i as f64 * width));
        }

        // Ensure the last break includes the maximum value
        breaks[bins] = max_val + f64::EPSILON;

        Self::from_breaks(breaks, closed, name)
    }

    /// Create quantile-based bins
    pub fn qcut(
        values: &[f64],
        bins: usize,
        closed: IntervalClosed,
        name: Option<String>,
    ) -> Result<Self> {
        if values.is_empty() {
            return Err(Error::InvalidValue("Cannot qcut empty values".to_string()));
        }

        let mut sorted_values = values.to_vec();
        sorted_values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let mut breaks = Vec::with_capacity(bins + 1);
        breaks.push(sorted_values[0]);

        for i in 1..bins {
            let index = (i as f64 / bins as f64 * sorted_values.len() as f64) as usize;
            let clamped_index = index.min(sorted_values.len() - 1);
            breaks.push(sorted_values[clamped_index]);
        }

        breaks.push(sorted_values[sorted_values.len() - 1] + f64::EPSILON);

        // Remove duplicates while preserving order
        let mut unique_breaks = Vec::new();
        for &brk in &breaks {
            if unique_breaks.is_empty()
                || (brk - unique_breaks[unique_breaks.len() - 1] as f64).abs() > f64::EPSILON
            {
                unique_breaks.push(brk);
            }
        }

        if unique_breaks.len() < 2 {
            return Err(Error::InvalidValue(
                "Not enough unique values for quantile bins".to_string(),
            ));
        }

        Self::from_breaks(unique_breaks, closed, name)
    }

    /// Find intervals containing a specific value
    pub fn find_intervals_containing(&self, value: f64) -> Vec<usize> {
        self.intervals
            .iter()
            .enumerate()
            .filter_map(|(i, interval)| {
                if interval.contains(value, &self.closed) {
                    Some(i)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Get interval labels
    pub fn labels(&self) -> Vec<&str> {
        self.intervals.iter().map(|i| i.label.as_str()).collect()
    }

    /// Get interval midpoints
    pub fn midpoints(&self) -> Vec<f64> {
        self.intervals.iter().map(|i| i.midpoint()).collect()
    }

    /// Get interval widths
    pub fn widths(&self) -> Vec<f64> {
        self.intervals.iter().map(|i| i.width()).collect()
    }
}

impl Index for IntervalIndex {
    fn len(&self) -> usize {
        self.intervals.len()
    }

    fn to_string_vec(&self) -> Vec<String> {
        self.intervals.iter().map(|i| i.label.clone()).collect()
    }

    fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    fn set_name(&mut self, name: Option<String>) {
        self.name = name;
    }

    fn has_duplicates(&self) -> bool {
        let mut seen = HashSet::new();
        self.intervals.iter().any(|i| !seen.insert(&i.label))
    }

    fn unique(&self) -> Result<Self> {
        let mut unique_intervals: Vec<Interval> = self.intervals.clone();
        unique_intervals.sort_by(|a, b| {
            a.left
                .partial_cmp(&b.left)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        unique_intervals.dedup_by(|a, b| a.label == b.label);

        Ok(IntervalIndex::new(
            unique_intervals,
            self.closed.clone(),
            self.name.clone(),
        ))
    }

    fn sort(&self, ascending: bool) -> Result<(Self, Vec<usize>)> {
        let mut indices: Vec<usize> = (0..self.intervals.len()).collect();

        if ascending {
            indices.sort_by(|&a, &b| {
                self.intervals[a]
                    .left
                    .partial_cmp(&self.intervals[b].left)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
        } else {
            indices.sort_by(|&a, &b| {
                self.intervals[b]
                    .left
                    .partial_cmp(&self.intervals[a].left)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
        }

        let sorted_intervals: Vec<Interval> =
            indices.iter().map(|&i| self.intervals[i].clone()).collect();
        let sorted_index =
            IntervalIndex::new(sorted_intervals, self.closed.clone(), self.name.clone());

        Ok((sorted_index, indices))
    }
}

/// Categorical index for memory-optimized categorical indexing
#[derive(Debug, Clone)]
pub struct CategoricalIndex {
    /// Category codes (indices into categories)
    pub codes: Vec<Option<usize>>,
    /// Unique categories
    pub categories: Vec<String>,
    /// Index name
    pub name: Option<String>,
    /// Whether categories are ordered
    pub ordered: bool,
}

impl CategoricalIndex {
    /// Create a new categorical index
    pub fn new(values: Vec<String>, name: Option<String>, ordered: bool) -> Self {
        let mut categories = Vec::new();
        let mut category_map = HashMap::new();
        let mut codes = Vec::with_capacity(values.len());

        for value in values {
            let code = if let Some(&existing_code) = category_map.get(&value) {
                existing_code
            } else {
                let new_code = categories.len();
                categories.push(value.clone());
                category_map.insert(value, new_code);
                new_code
            };
            codes.push(Some(code));
        }

        Self {
            codes,
            categories,
            name,
            ordered,
        }
    }

    /// Create categorical index with predefined categories
    pub fn with_categories(
        values: Vec<String>,
        categories: Vec<String>,
        name: Option<String>,
        ordered: bool,
    ) -> Result<Self> {
        let category_map: HashMap<String, usize> = categories
            .iter()
            .enumerate()
            .map(|(i, cat)| (cat.clone(), i))
            .collect();

        let mut codes = Vec::with_capacity(values.len());

        for value in values {
            let code = category_map.get(&value).copied();
            codes.push(code);
        }

        Ok(Self {
            codes,
            categories,
            name,
            ordered,
        })
    }

    /// Get category values
    pub fn values(&self) -> Vec<Option<String>> {
        self.codes
            .iter()
            .map(|&code| code.map(|c| self.categories[c].clone()))
            .collect()
    }

    /// Get category counts
    pub fn value_counts(&self) -> HashMap<String, usize> {
        let mut counts = HashMap::new();
        for &code in &self.codes {
            if let Some(code) = code {
                let category = &self.categories[code];
                *counts.entry(category.clone()).or_insert(0) += 1;
            }
        }
        counts
    }

    /// Add new categories
    pub fn add_categories(&mut self, new_categories: Vec<String>) -> Result<()> {
        let existing_set: HashSet<_> = self.categories.iter().collect();
        let categories_to_add: Vec<String> = new_categories
            .into_iter()
            .filter(|cat| !existing_set.contains(cat))
            .collect();

        self.categories.extend(categories_to_add);
        Ok(())
    }

    /// Remove categories (and set corresponding codes to None)
    pub fn remove_categories(&mut self, categories_to_remove: Vec<String>) -> Result<()> {
        let remove_set: HashSet<_> = categories_to_remove.iter().collect();
        let mut old_to_new_index = HashMap::new();
        let mut new_categories = Vec::new();

        for (old_idx, category) in self.categories.iter().enumerate() {
            if !remove_set.contains(category) {
                old_to_new_index.insert(old_idx, new_categories.len());
                new_categories.push(category.clone());
            }
        }

        // Update codes
        for code in &mut self.codes {
            if let Some(old_code) = *code {
                *code = old_to_new_index.get(&old_code).copied();
            }
        }

        self.categories = new_categories;
        Ok(())
    }

    /// Memory usage in bytes
    pub fn memory_usage(&self) -> usize {
        let codes_size = self.codes.len() * std::mem::size_of::<Option<usize>>();
        let categories_size: usize = self.categories.iter().map(|s| s.len()).sum();
        let name_size = self.name.as_ref().map_or(0, |s| s.len());

        codes_size + categories_size + name_size + std::mem::size_of::<Self>()
    }
}

impl Index for CategoricalIndex {
    fn len(&self) -> usize {
        self.codes.len()
    }

    fn to_string_vec(&self) -> Vec<String> {
        self.codes
            .iter()
            .map(|&code| match code {
                Some(c) => self.categories[c].clone(),
                None => "NaN".to_string(),
            })
            .collect()
    }

    fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    fn set_name(&mut self, name: Option<String>) {
        self.name = name;
    }

    fn has_duplicates(&self) -> bool {
        let mut seen = HashSet::new();
        self.codes.iter().any(|&code| !seen.insert(code))
    }

    fn unique(&self) -> Result<Self> {
        let mut unique_codes = Vec::new();
        let mut seen = HashSet::new();

        for &code in &self.codes {
            if seen.insert(code) {
                unique_codes.push(code);
            }
        }

        Ok(CategoricalIndex {
            codes: unique_codes,
            categories: self.categories.clone(),
            name: self.name.clone(),
            ordered: self.ordered,
        })
    }

    fn sort(&self, ascending: bool) -> Result<(Self, Vec<usize>)> {
        let mut indices: Vec<usize> = (0..self.codes.len()).collect();

        indices.sort_by(|&a, &b| match (self.codes[a], self.codes[b]) {
            (Some(code_a), Some(code_b)) => {
                let cat_a = &self.categories[code_a];
                let cat_b = &self.categories[code_b];
                if ascending {
                    cat_a.cmp(cat_b)
                } else {
                    cat_b.cmp(cat_a)
                }
            }
            (Some(_), None) => {
                if ascending {
                    std::cmp::Ordering::Less
                } else {
                    std::cmp::Ordering::Greater
                }
            }
            (None, Some(_)) => {
                if ascending {
                    std::cmp::Ordering::Greater
                } else {
                    std::cmp::Ordering::Less
                }
            }
            (None, None) => std::cmp::Ordering::Equal,
        });

        let sorted_codes: Vec<Option<usize>> = indices.iter().map(|&i| self.codes[i]).collect();
        let sorted_index = CategoricalIndex {
            codes: sorted_codes,
            categories: self.categories.clone(),
            name: self.name.clone(),
            ordered: self.ordered,
        };

        Ok((sorted_index, indices))
    }
}

/// Index set operations implementation
pub struct IndexOperations;

impl IndexOperations {
    /// Union of two string-based indexes (generic implementation)
    pub fn union_string_indexes(left: &[String], right: &[String]) -> Vec<String> {
        let mut result = left.to_vec();
        let left_set: HashSet<_> = left.iter().collect();

        for item in right {
            if !left_set.contains(item) {
                result.push(item.clone());
            }
        }

        result
    }

    /// Intersection of two string-based indexes
    pub fn intersection_string_indexes(left: &[String], right: &[String]) -> Vec<String> {
        let right_set: HashSet<_> = right.iter().collect();

        left.iter()
            .filter(|item| right_set.contains(item))
            .cloned()
            .collect()
    }

    /// Difference of two string-based indexes (left - right)
    pub fn difference_string_indexes(left: &[String], right: &[String]) -> Vec<String> {
        let right_set: HashSet<_> = right.iter().collect();

        left.iter()
            .filter(|item| !right_set.contains(item))
            .cloned()
            .collect()
    }

    /// Symmetric difference of two string-based indexes
    pub fn symmetric_difference_string_indexes(left: &[String], right: &[String]) -> Vec<String> {
        let left_set: HashSet<_> = left.iter().collect();
        let right_set: HashSet<_> = right.iter().collect();

        let mut result = Vec::new();

        // Items in left but not in right
        for item in left {
            if !right_set.contains(item) {
                result.push(item.clone());
            }
        }

        // Items in right but not in left
        for item in right {
            if !left_set.contains(item) {
                result.push(item.clone());
            }
        }

        result
    }
}

/// Extension trait to add advanced indexing to DataFrame
pub trait AdvancedIndexingExt {
    /// Set datetime index
    fn set_datetime_index(
        &self,
        column: &str,
        name: Option<String>,
    ) -> Result<(DataFrame, DatetimeIndex)>;

    /// Set period index
    fn set_period_index(
        &self,
        start_date: NaiveDate,
        frequency: PeriodFrequency,
        name: Option<String>,
    ) -> Result<(DataFrame, PeriodIndex)>;

    /// Set interval index by cutting a column
    fn set_interval_index_cut(
        &self,
        column: &str,
        bins: usize,
        closed: IntervalClosed,
        name: Option<String>,
    ) -> Result<(DataFrame, IntervalIndex)>;

    /// Set interval index by quantile cutting a column
    fn set_interval_index_qcut(
        &self,
        column: &str,
        bins: usize,
        closed: IntervalClosed,
        name: Option<String>,
    ) -> Result<(DataFrame, IntervalIndex)>;

    /// Set categorical index
    fn set_categorical_index(
        &self,
        column: &str,
        ordered: bool,
        name: Option<String>,
    ) -> Result<(DataFrame, CategoricalIndex)>;
}

impl AdvancedIndexingExt for DataFrame {
    fn set_datetime_index(
        &self,
        column: &str,
        name: Option<String>,
    ) -> Result<(DataFrame, DatetimeIndex)> {
        let column_values = self.get_column_string_values(column)?;
        let mut datetime_values = Vec::new();

        for value in &column_values {
            let dt = NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S")
                .or_else(|_| NaiveDateTime::parse_from_str(value, "%Y-%m-%d"))
                .map_err(|_| Error::InvalidValue(format!("Cannot parse datetime: {}", value)))?;
            datetime_values.push(dt);
        }

        let index = DatetimeIndex::new(datetime_values, name);
        let df_without_index = self.drop_columns(&[column.to_string()])?;

        Ok((df_without_index, index))
    }

    fn set_period_index(
        &self,
        start_date: NaiveDate,
        frequency: PeriodFrequency,
        name: Option<String>,
    ) -> Result<(DataFrame, PeriodIndex)> {
        let row_count = self.row_count();

        // Calculate end date based on row count and frequency
        let end_date = match frequency {
            PeriodFrequency::Daily => start_date + Duration::days(row_count as i64 - 1),
            PeriodFrequency::Weekly => start_date + Duration::weeks(row_count as i64 - 1),
            PeriodFrequency::Monthly => {
                let mut current = start_date;
                for _ in 0..(row_count - 1) {
                    current = if current.month() == 12 {
                        NaiveDate::from_ymd_opt(current.year() + 1, 1, 1)
                    } else {
                        NaiveDate::from_ymd_opt(current.year(), current.month() + 1, 1)
                    }
                    .ok_or_else(|| Error::InvalidValue("Invalid date calculation".to_string()))?;
                }
                current
            }
            PeriodFrequency::Quarterly => {
                let mut current = start_date;
                for _ in 0..(row_count - 1) {
                    let quarter = ((current.month() - 1) / 3) + 1;
                    current = if quarter == 4 {
                        NaiveDate::from_ymd_opt(current.year() + 1, 1, 1)
                    } else {
                        NaiveDate::from_ymd_opt(current.year(), ((quarter) * 3) + 1, 1)
                    }
                    .ok_or_else(|| {
                        Error::InvalidValue("Invalid quarter calculation".to_string())
                    })?;
                }
                current
            }
            PeriodFrequency::Annual => NaiveDate::from_ymd_opt(
                start_date.year() + row_count as i32 - 1,
                start_date.month(),
                start_date.day(),
            )
            .ok_or_else(|| Error::InvalidValue("Invalid year calculation".to_string()))?,
        };

        let index = PeriodIndex::period_range(start_date, end_date, frequency, name)?;
        Ok((self.clone(), index))
    }

    fn set_interval_index_cut(
        &self,
        column: &str,
        bins: usize,
        closed: IntervalClosed,
        name: Option<String>,
    ) -> Result<(DataFrame, IntervalIndex)> {
        let column_values = self.get_column_string_values(column)?;
        let mut numeric_values = Vec::new();

        for value in &column_values {
            let num = value
                .parse::<f64>()
                .map_err(|_| Error::InvalidValue(format!("Cannot parse number: {}", value)))?;
            numeric_values.push(num);
        }

        let index = IntervalIndex::cut(&numeric_values, bins, closed, name)?;
        let df_without_index = self.drop_columns(&[column.to_string()])?;

        Ok((df_without_index, index))
    }

    fn set_interval_index_qcut(
        &self,
        column: &str,
        bins: usize,
        closed: IntervalClosed,
        name: Option<String>,
    ) -> Result<(DataFrame, IntervalIndex)> {
        let column_values = self.get_column_string_values(column)?;
        let mut numeric_values = Vec::new();

        for value in &column_values {
            let num = value
                .parse::<f64>()
                .map_err(|_| Error::InvalidValue(format!("Cannot parse number: {}", value)))?;
            numeric_values.push(num);
        }

        let index = IntervalIndex::qcut(&numeric_values, bins, closed, name)?;
        let df_without_index = self.drop_columns(&[column.to_string()])?;

        Ok((df_without_index, index))
    }

    fn set_categorical_index(
        &self,
        column: &str,
        ordered: bool,
        name: Option<String>,
    ) -> Result<(DataFrame, CategoricalIndex)> {
        let column_values = self.get_column_string_values(column)?;
        let index = CategoricalIndex::new(column_values, name, ordered);
        let df_without_index = self.drop_columns(&[column.to_string()])?;

        Ok((df_without_index, index))
    }
}