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
use rayon::prelude::*;
use std::cmp::Ordering;
use std::collections::HashMap;
use crate::column::{Column, ColumnTrait, ColumnType};
use crate::error::{Error, Result};
use crate::optimized::split_dataframe::core::OptimizedDataFrame;
impl OptimizedDataFrame {
/// Sort DataFrame by column
///
/// # Arguments
/// * `by` - Name of the column to sort by
/// * `ascending` - Whether to sort in ascending order
///
/// # Returns
/// * `Result<Self>` - A new DataFrame that is sorted
pub fn sort_by(&self, by: &str, ascending: bool) -> Result<Self> {
// Get column index
let column_idx = self
.column_indices
.get(by)
.ok_or_else(|| Error::ColumnNotFound(by.to_string()))?;
let column = &self.columns[*column_idx];
// Create an array of row indices (from 0 to row_count-1)
let mut indices: Vec<usize> = (0..self.row_count()).collect();
// Sort based on column type
match column.column_type() {
ColumnType::Int64 => {
let col = column.as_int64().ok_or_else(|| {
Error::TypeMismatch("column type check failed for Int64".into())
})?;
// Create pairs of row index and value
let mut pairs: Vec<(usize, Option<i64>)> = indices
.iter()
.map(|&idx| (idx, col.get(idx).ok().flatten()))
.collect();
// Sort: NULL values are placed at the end
pairs.sort_by(|a, b| match (&a.1, &b.1) {
(None, None) => Ordering::Equal,
(None, _) => Ordering::Greater,
(_, None) => Ordering::Less,
(Some(val_a), Some(val_b)) => {
if ascending {
val_a.cmp(val_b)
} else {
val_b.cmp(val_a)
}
}
});
// Extract sorted row indices
indices = pairs.into_iter().map(|(idx, _)| idx).collect();
}
ColumnType::Float64 => {
let col = column.as_float64().ok_or_else(|| {
Error::TypeMismatch("column type check failed for Float64".into())
})?;
// Create pairs of row index and value
let mut pairs: Vec<(usize, Option<f64>)> = indices
.iter()
.map(|&idx| (idx, col.get(idx).ok().flatten()))
.collect();
// Sort: NULL values are placed at the end
pairs.sort_by(|a, b| match (&a.1, &b.1) {
(None, None) => Ordering::Equal,
(None, _) => Ordering::Greater,
(_, None) => Ordering::Less,
(Some(val_a), Some(val_b)) => {
if ascending {
val_a.partial_cmp(val_b).unwrap_or(Ordering::Equal)
} else {
val_b.partial_cmp(val_a).unwrap_or(Ordering::Equal)
}
}
});
// Extract sorted row indices
indices = pairs.into_iter().map(|(idx, _)| idx).collect();
}
ColumnType::String => {
let col = column.as_string().ok_or_else(|| {
Error::TypeMismatch("column type check failed for String".into())
})?;
// Create pairs of row index and value
let mut pairs: Vec<(usize, Option<String>)> = indices
.iter()
.map(|&idx| (idx, col.get(idx).ok().flatten().map(|s| s.to_string())))
.collect();
// Sort: NULL values are placed at the end
pairs.sort_by(|a, b| match (&a.1, &b.1) {
(None, None) => Ordering::Equal,
(None, _) => Ordering::Greater,
(_, None) => Ordering::Less,
(Some(val_a), Some(val_b)) => {
if ascending {
val_a.cmp(val_b)
} else {
val_b.cmp(val_a)
}
}
});
// Extract sorted row indices
indices = pairs.into_iter().map(|(idx, _)| idx).collect();
}
ColumnType::Boolean => {
let col = column.as_boolean().ok_or_else(|| {
Error::TypeMismatch("column type check failed for Boolean".into())
})?;
// Create pairs of row index and value
let mut pairs: Vec<(usize, Option<bool>)> = indices
.iter()
.map(|&idx| (idx, col.get(idx).ok().flatten()))
.collect();
// Sort: NULL values are placed at the end
pairs.sort_by(|a, b| match (&a.1, &b.1) {
(None, None) => Ordering::Equal,
(None, _) => Ordering::Greater,
(_, None) => Ordering::Less,
(Some(val_a), Some(val_b)) => {
if ascending {
val_a.cmp(val_b)
} else {
val_b.cmp(val_a)
}
}
});
// Extract sorted row indices
indices = pairs.into_iter().map(|(idx, _)| idx).collect();
}
}
// Create a new DataFrame from sorted row indices
self.select_rows_by_indices_internal(&indices)
}
/// Sort DataFrame by multiple columns
///
/// # Arguments
/// * `by` - Array of column names to sort by
/// * `ascending` - Array of boolean flags indicating ascending/descending order for each column (if None, all are ascending)
///
/// # Returns
/// * `Result<Self>` - A new DataFrame that is sorted
pub fn sort_by_columns(&self, by: &[&str], ascending: Option<&[bool]>) -> Result<Self> {
if by.is_empty() {
return Err(Error::EmptyColumnList);
}
// Verify column names exist
for &col_name in by {
if !self.column_indices.contains_key(col_name) {
return Err(Error::ColumnNotFound(col_name.to_string()));
}
}
// Set ascending array
let is_ascending: Vec<bool> = match ascending {
Some(asc) => {
if asc.len() != by.len() {
return Err(Error::InconsistentArrayLengths {
expected: by.len(),
found: asc.len(),
});
}
asc.to_vec()
}
None => vec![true; by.len()], // Default is ascending
};
// Create an array of row indices (from 0 to row_count-1)
let mut indices: Vec<usize> = (0..self.row_count()).collect();
// Sort by multiple keys
indices.sort_by(|&a, &b| {
// Compare each column
for (col_idx, (&col_name, &asc)) in by.iter().zip(is_ascending.iter()).enumerate() {
let column_idx = self.column_indices[col_name];
let column = &self.columns[column_idx];
let cmp = match column.column_type() {
ColumnType::Int64 => {
let col = column
.as_int64()
.expect("column type already validated in match");
let val_a = col.get(a).ok().flatten();
let val_b = col.get(b).ok().flatten();
match (val_a, val_b) {
(None, None) => Ordering::Equal,
(None, _) => Ordering::Greater,
(_, None) => Ordering::Less,
(Some(v_a), Some(v_b)) => {
if asc {
v_a.cmp(&v_b)
} else {
v_b.cmp(&v_a)
}
}
}
}
ColumnType::Float64 => {
let col = column
.as_float64()
.expect("column type already validated in match");
let val_a = col.get(a).ok().flatten();
let val_b = col.get(b).ok().flatten();
match (val_a, val_b) {
(None, None) => Ordering::Equal,
(None, _) => Ordering::Greater,
(_, None) => Ordering::Less,
(Some(v_a), Some(v_b)) => {
if asc {
v_a.partial_cmp(&v_b).unwrap_or(Ordering::Equal)
} else {
v_b.partial_cmp(&v_a).unwrap_or(Ordering::Equal)
}
}
}
}
ColumnType::String => {
let col = column
.as_string()
.expect("column type already validated in match");
let val_a = col.get(a).ok().flatten().map(|s| s.to_string());
let val_b = col.get(b).ok().flatten().map(|s| s.to_string());
match (val_a, val_b) {
(None, None) => Ordering::Equal,
(None, _) => Ordering::Greater,
(_, None) => Ordering::Less,
(Some(v_a), Some(v_b)) => {
if asc {
v_a.cmp(&v_b)
} else {
v_b.cmp(&v_a)
}
}
}
}
ColumnType::Boolean => {
let col = column
.as_boolean()
.expect("column type already validated in match");
let val_a = col.get(a).ok().flatten();
let val_b = col.get(b).ok().flatten();
match (val_a, val_b) {
(None, None) => Ordering::Equal,
(None, _) => Ordering::Greater,
(_, None) => Ordering::Less,
(Some(v_a), Some(v_b)) => {
if asc {
v_a.cmp(&v_b)
} else {
v_b.cmp(&v_a)
}
}
}
}
};
// Return result if not equal
if cmp != Ordering::Equal {
return cmp;
}
// Proceed to the next column
}
// If all columns are equal
Ordering::Equal
});
// Create a new DataFrame from sorted row indices
self.select_rows_by_indices_internal(&indices)
}
/// Select rows based on row indices (using implementation from select module)
fn select_rows_by_indices_internal(&self, indices: &[usize]) -> Result<Self> {
// Use function implemented in select.rs
use crate::optimized::split_dataframe::select;
select::select_rows_by_indices_impl(self, indices)
}
}