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
use std::collections::HashMap;
use std::fmt::Debug;
use crate::core::error::{Error, Result};
use crate::dataframe::base::DataFrame;
use crate::series::base::Series;
// Removed temporal and window imports to break circular dependencies
/// Axis for function application
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Axis {
/// Apply function to each column
Column = 0,
/// Apply function to each row
Row = 1,
}
/// Apply functionality for DataFrames (simplified to avoid compilation issues)
pub trait ApplyExt {
/// Apply a function to each column or row
fn apply<F>(&self, f: F, axis: Axis, result_name: Option<String>) -> Result<Series<String>>
where
F: Fn(&Series<String>) -> String;
/// Apply a function to each element
fn applymap<F>(&self, f: F) -> Result<DataFrame>
where
F: Fn(&str) -> String;
/// Replace values based on a condition
fn mask<F>(&self, condition: F, other: &str) -> Result<DataFrame>
where
F: Fn(&str) -> bool;
/// Replace values based on a condition (inverse of mask)
fn where_func<F>(&self, condition: F, other: &str) -> Result<DataFrame>
where
F: Fn(&str) -> bool;
/// Replace values with corresponding values
fn replace(&self, replace_map: &HashMap<String, String>) -> Result<DataFrame>;
/// Detect duplicate rows
fn duplicated(&self, subset: Option<&[String]>, keep: Option<&str>) -> Result<Series<bool>>;
/// Drop duplicate rows
fn drop_duplicates(&self, subset: Option<&[String]>, keep: Option<&str>) -> Result<DataFrame>;
}
/// Implementation of ApplyExt for DataFrame
impl ApplyExt for DataFrame {
fn apply<F>(&self, f: F, axis: Axis, result_name: Option<String>) -> Result<Series<String>>
where
F: Fn(&Series<String>) -> String,
{
match axis {
Axis::Column => {
let mut results = Vec::new();
for column_name in self.column_names() {
// Get column as string series
let string_values = self.get_column_string_values(column_name)?;
let series = Series::new(string_values, Some(column_name.to_string()))?;
// Apply function to the series
let result = f(&series);
results.push(result);
}
Series::new(results, result_name)
}
Axis::Row => {
let mut results = Vec::new();
// Materialize every column ONCE up front. Previously each
// column was re-fetched (full clone) inside the row loop →
// O(rows²·cols) time and allocations; now O(rows·cols).
let columns: Vec<Vec<String>> = self
.column_names()
.iter()
.map(|name| self.get_column_string_values(name))
.collect::<Result<Vec<_>>>()?;
for row_idx in 0..self.row_count() {
let mut row_values = Vec::with_capacity(columns.len());
// Collect all values for this row from the cached columns
for column in &columns {
if row_idx < column.len() {
row_values.push(column[row_idx].clone());
}
}
// Create series for this row and apply function
let row_series = Series::new(row_values, Some(format!("row_{}", row_idx)))?;
let result = f(&row_series);
results.push(result);
}
Series::new(results, result_name)
}
}
}
fn applymap<F>(&self, f: F) -> Result<DataFrame>
where
F: Fn(&str) -> String,
{
let mut result = DataFrame::new();
for column_name in self.column_names() {
// Get column values as strings
let string_values = self.get_column_string_values(column_name)?;
// Apply function to each element
let transformed_values: Vec<String> = string_values.iter().map(|val| f(val)).collect();
// Create new series with transformed values
let new_series = Series::new(transformed_values, Some(column_name.to_string()))?;
result.add_column(column_name.to_string(), new_series)?;
}
Ok(result)
}
fn mask<F>(&self, condition: F, other: &str) -> Result<DataFrame>
where
F: Fn(&str) -> bool,
{
let mut result = DataFrame::new();
for column_name in self.column_names() {
// Get column values as strings
let string_values = self.get_column_string_values(column_name)?;
// Apply mask: replace values that satisfy condition with 'other'
let masked_values: Vec<String> = string_values
.iter()
.map(|val| {
if condition(val) {
other.to_string()
} else {
val.clone()
}
})
.collect();
// Create new series with masked values
let new_series = Series::new(masked_values, Some(column_name.to_string()))?;
result.add_column(column_name.to_string(), new_series)?;
}
Ok(result)
}
fn where_func<F>(&self, condition: F, other: &str) -> Result<DataFrame>
where
F: Fn(&str) -> bool,
{
let mut result = DataFrame::new();
for column_name in self.column_names() {
// Get column values as strings
let string_values = self.get_column_string_values(column_name)?;
// Apply where: keep values that satisfy condition, replace others with 'other'
let where_values: Vec<String> = string_values
.iter()
.map(|val| {
if condition(val) {
val.clone()
} else {
other.to_string()
}
})
.collect();
// Create new series with where values
let new_series = Series::new(where_values, Some(column_name.to_string()))?;
result.add_column(column_name.to_string(), new_series)?;
}
Ok(result)
}
fn replace(&self, replace_map: &HashMap<String, String>) -> Result<DataFrame> {
let mut result = DataFrame::new();
for column_name in self.column_names() {
// Get column values as strings
let string_values = self.get_column_string_values(column_name)?;
// Apply replacements
let replaced_values: Vec<String> = string_values
.iter()
.map(|val| replace_map.get(val).cloned().unwrap_or_else(|| val.clone()))
.collect();
// Create new series with replaced values
let new_series = Series::new(replaced_values, Some(column_name.to_string()))?;
result.add_column(column_name.to_string(), new_series)?;
}
Ok(result)
}
fn duplicated(&self, subset: Option<&[String]>, keep: Option<&str>) -> Result<Series<bool>> {
let keep_option = keep.unwrap_or("first");
let mut result = vec![false; self.row_count()];
// Determine which columns to check for duplicates
let columns_to_check = if let Some(subset_cols) = subset {
subset_cols.to_vec()
} else {
self.column_names().to_vec()
};
// Validate that all subset columns exist
for col_name in &columns_to_check {
if !self.contains_column(col_name) {
return Err(Error::ColumnNotFound(col_name.to_string()));
}
}
// Materialize each checked column ONCE, then build per-row keys. The
// column fetch was previously inside the row loop, re-allocating the
// whole column for every row → O(rows²·cols). Now O(rows·cols).
let columns: Vec<Vec<String>> = columns_to_check
.iter()
.map(|col_name| self.get_column_string_values(col_name))
.collect::<Result<Vec<_>>>()?;
let mut row_data = Vec::with_capacity(self.row_count());
for row_idx in 0..self.row_count() {
let mut row_values = Vec::with_capacity(columns.len());
for column_values in &columns {
if row_idx < column_values.len() {
row_values.push(column_values[row_idx].clone());
}
}
row_data.push(row_values);
}
// Find duplicates based on keep strategy
match keep_option {
"first" => {
let mut seen = std::collections::HashSet::new();
for (idx, row) in row_data.iter().enumerate() {
if seen.contains(row) {
result[idx] = true;
} else {
seen.insert(row.clone());
}
}
}
"last" => {
let mut seen = std::collections::HashSet::new();
// Process in reverse to mark earlier occurrences as duplicates
for (idx, row) in row_data.iter().enumerate().rev() {
if seen.contains(row) {
result[idx] = true;
} else {
seen.insert(row.clone());
}
}
}
"false" => {
// Mark all duplicates (both first and subsequent occurrences)
let mut counts = std::collections::HashMap::new();
for row in &row_data {
*counts.entry(row.clone()).or_insert(0) += 1;
}
for (idx, row) in row_data.iter().enumerate() {
if counts[row] > 1 {
result[idx] = true;
}
}
}
_ => {
return Err(Error::InvalidValue(format!(
"Invalid keep option: {}. Must be 'first', 'last', or 'false'",
keep_option
)));
}
}
Series::new(result, Some("duplicated".to_string()))
}
fn drop_duplicates(&self, subset: Option<&[String]>, keep: Option<&str>) -> Result<DataFrame> {
let keep_option = keep.unwrap_or("first");
// Determine which columns to check for duplicates
let columns_to_check = if let Some(subset_cols) = subset {
subset_cols.to_vec()
} else {
self.column_names().to_vec()
};
// Validate that all subset columns exist
for col_name in &columns_to_check {
if !self.contains_column(col_name) {
return Err(Error::ColumnNotFound(col_name.to_string()));
}
}
// Materialize each checked column ONCE, then build per-row keys. The
// column fetch was previously inside the row loop, re-allocating the
// whole column for every row → O(rows²·cols). Now O(rows·cols).
let columns: Vec<Vec<String>> = columns_to_check
.iter()
.map(|col_name| self.get_column_string_values(col_name))
.collect::<Result<Vec<_>>>()?;
let mut row_data = Vec::with_capacity(self.row_count());
for row_idx in 0..self.row_count() {
let mut row_values = Vec::with_capacity(columns.len());
for column_values in &columns {
if row_idx < column_values.len() {
row_values.push(column_values[row_idx].clone());
}
}
row_data.push(row_values);
}
// Determine which rows to keep
let mut rows_to_keep = Vec::new();
match keep_option {
"first" => {
let mut seen = std::collections::HashSet::new();
for (idx, row) in row_data.iter().enumerate() {
if !seen.contains(row) {
seen.insert(row.clone());
rows_to_keep.push(idx);
}
}
}
"last" => {
let mut seen = std::collections::HashSet::new();
// Process in reverse to keep last occurrences
for (idx, row) in row_data.iter().enumerate().rev() {
if !seen.contains(row) {
seen.insert(row.clone());
rows_to_keep.push(idx);
}
}
rows_to_keep.reverse(); // Restore original order
}
"false" => {
// Keep no duplicates (remove all duplicate rows)
let mut counts = std::collections::HashMap::new();
for row in &row_data {
*counts.entry(row.clone()).or_insert(0) += 1;
}
for (idx, row) in row_data.iter().enumerate() {
if counts[row] == 1 {
rows_to_keep.push(idx);
}
}
}
_ => {
return Err(Error::InvalidValue(format!(
"Invalid keep option: {}. Must be 'first', 'last', or 'false'",
keep_option
)));
}
}
// Create result DataFrame with selected rows
let mut result = DataFrame::new();
for column_name in self.column_names() {
let column_values = self.get_column_string_values(column_name)?;
let filtered_values: Vec<String> = rows_to_keep
.iter()
.filter_map(|&row_idx| column_values.get(row_idx).cloned())
.collect();
let new_series = Series::new(filtered_values, Some(column_name.to_string()))?;
result.add_column(column_name.to_string(), new_series)?;
}
Ok(result)
}
// Window operations removed to break circular dependencies and fix compilation timeouts
}
/// Re-export Axis for backward compatibility
pub use crate::dataframe::apply::Axis as LegacyAxis;