csv_processor 0.1.10

A fast command-line CSV analysis tool with automatic type inference and comprehensive statistics
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
use crate::{CellValue, Dtype};
use serde_json::{json, Value};

pub trait ColumnArray: std::fmt::Debug {
    fn len(&self) -> usize;
    fn dtype(&self) -> Dtype;
    fn get(&self, index: usize) -> Option<CellValue>;
    fn null_count(&self) -> usize;
    fn non_null_count(&self) -> usize {
        self.len() - self.null_count()
    }
    fn as_any(&self) -> &dyn std::any::Any;

    fn mean(&self) -> Option<f64> {
        None
    }
    fn sum(&self) -> Option<f64> {
        None
    }
    fn min(&self) -> Option<f64> {
        None
    }
    fn max(&self) -> Option<f64> {
        None
    }

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn to_json(&self) -> Vec<serde_json::Value>;
}

#[derive(Debug)]
pub struct IntegerColumn(pub Vec<Option<i64>>);

#[derive(Debug)]
pub struct FloatColumn(pub Vec<Option<f64>>);

#[derive(Debug)]
pub struct StringColumn(pub Vec<Option<String>>);

#[derive(Debug)]
pub struct BooleanColumn(pub Vec<Option<bool>>);

impl ColumnArray for IntegerColumn {
    fn to_json(&self) -> Vec<serde_json::Value> {
        self.0
            .iter()
            .map(|&x| match x {
                Some(x) => json!(x),
                None => Value::Null,
            })
            .collect()
    }

    fn dtype(&self) -> Dtype {
        Dtype::Integer
    }

    fn get(&self, index: usize) -> Option<CellValue> {
        self.0.get(index)?.map(CellValue::Integer)
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    fn null_count(&self) -> usize {
        self.0.iter().filter(|x| x.is_none()).count()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn sum(&self) -> Option<f64> {
        let sum: i64 = self.0.iter().filter_map(|&x| x).sum();
        Some(sum as f64)
    }

    fn max(&self) -> Option<f64> {
        self.0.iter().filter_map(|&x| x).max().map(|x| x as f64)
    }

    fn min(&self) -> Option<f64> {
        self.0.iter().filter_map(|&x| x).min().map(|x| x as f64)
    }

    fn mean(&self) -> Option<f64> {
        let count = self.non_null_count();
        if count == 0 {
            return None;
        }
        let sum: i64 = self.0.iter().filter_map(|&x| x).sum();
        Some(sum as f64 / count as f64)
    }
}

impl ColumnArray for FloatColumn {
    fn to_json(&self) -> Vec<serde_json::Value> {
        self.0
            .iter()
            .map(|&x| match x {
                Some(x) => json!(x),
                None => Value::Null,
            })
            .collect()
    }

    fn dtype(&self) -> Dtype {
        Dtype::Float
    }

    fn get(&self, index: usize) -> Option<CellValue> {
        self.0.get(index)?.map(CellValue::Float)
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    fn null_count(&self) -> usize {
        self.0.iter().filter(|x| x.is_none()).count()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn sum(&self) -> Option<f64> {
        Some(
            self.0
                .iter()
                .filter_map(|&x| x)
                .filter(|x| !x.is_nan())
                .sum(),
        )
    }

    fn max(&self) -> Option<f64> {
        self.0
            .iter()
            .filter_map(|&x| x) // Remove None
            .filter(|x| !x.is_nan()) // Remove NaN
            .max_by(|a, b| a.partial_cmp(b).unwrap()) // Safe to unwrap now
    }

    fn min(&self) -> Option<f64> {
        self.0
            .iter()
            .filter_map(|&x| x)
            .filter(|x| !x.is_nan())
            .min_by(|a, b| a.partial_cmp(b).unwrap())
    }

    fn mean(&self) -> Option<f64> {
        let valid_values: Vec<f64> = self
            .0
            .iter()
            .filter_map(|&x| x)
            .filter(|x| !x.is_nan())
            .collect();

        if valid_values.is_empty() {
            return Some(0.0);
        }

        let sum: f64 = valid_values.iter().sum();
        Some(sum / valid_values.len() as f64)
    }
}

impl ColumnArray for StringColumn {
    fn to_json(&self) -> Vec<serde_json::Value> {
        self.0
            .iter()
            .map(|x| match &x {
                Some(ref x) => json!(x),
                None => Value::Null,
            })
            .collect()
    }

    fn dtype(&self) -> Dtype {
        Dtype::Str
    }

    fn get(&self, index: usize) -> Option<CellValue> {
        self.0.get(index)?.clone().map(CellValue::Str)
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    fn null_count(&self) -> usize {
        self.0.iter().filter(|x| x.is_none()).count()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl ColumnArray for BooleanColumn {
    fn to_json(&self) -> Vec<serde_json::Value> {
        self.0
            .iter()
            .map(|&x| match x {
                Some(x) => json!(x),
                None => Value::Null,
            })
            .collect()
    }

    fn dtype(&self) -> Dtype {
        Dtype::Boolean
    }

    fn get(&self, index: usize) -> Option<CellValue> {
        self.0.get(index)?.map(CellValue::Boolean)
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    fn null_count(&self) -> usize {
        self.0.iter().filter(|x| x.is_none()).count()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn sum(&self) -> Option<f64> {
        Some(self.0.iter().filter_map(|&x| x).filter(|&x| x).count() as f64)
    }

    fn min(&self) -> Option<f64> {
        if self.non_null_count() == 0 {
            return Some(0.0);
        }
        // let has_false = self.0.iter().any(|&x| x == Some(false));
        let has_false = self.0.contains(&Some(false));
        Some(if has_false { 0.0 } else { 1.0 })
    }

    fn max(&self) -> Option<f64> {
        if self.non_null_count() == 0 {
            return Some(0.0);
        }
        // let has_true = self.0.iter().any(|&x| x == Some(true));
        let has_true = self.0.contains(&Some(true));
        Some(if has_true { 1.0 } else { 0.0 })
    }

    fn mean(&self) -> Option<f64> {
        let non_nulls = self.non_null_count();
        if non_nulls == 0 {
            return None;
        }
        let sum = self.0.iter().filter_map(|&x| x).filter(|&x| x).count();
        Some(sum as f64 / non_nulls as f64)
    }
}

pub fn parse_column(column: Vec<&str>) -> Box<dyn ColumnArray> {
    if let Some(array) = parse_integers(&column) {
        return Box::new(IntegerColumn(array));
    }

    if let Some(array) = parse_floats(&column) {
        return Box::new(FloatColumn(array));
    }

    if let Some(array) = parse_bools(&column) {
        return Box::new(BooleanColumn(array));
    }

    Box::new(StringColumn(parse_strings(&column)))
}

fn parse_integers(raw_data: &[&str]) -> Option<Vec<Option<i64>>> {
    let mut result = Vec::new();

    for cell in raw_data {
        if cell.is_empty() || cell.to_lowercase() == "na" {
            result.push(None);
        } else {
            match cell.parse::<i64>() {
                Ok(val) => result.push(Some(val)),
                Err(_) => return None,
            }
        }
    }
    Some(result)
}

fn parse_floats(raw_data: &[&str]) -> Option<Vec<Option<f64>>> {
    let mut result = Vec::new();

    for cell in raw_data {
        if cell.is_empty() || cell.to_lowercase() == "na" {
            result.push(None);
        } else {
            match cell.parse::<f64>() {
                Ok(val) => result.push(Some(val)),
                Err(_) => return None,
            }
        }
    }
    Some(result)
}

fn parse_strings(raw_data: &[&str]) -> Vec<Option<String>> {
    raw_data
        .iter()
        .map(|x| {
            if x.is_empty() || x.to_lowercase() == "na" {
                None
            } else {
                Some(x.to_string())
            }
        })
        .collect()
}

fn parse_bools(raw_data: &[&str]) -> Option<Vec<Option<bool>>> {
    let mut result = Vec::new();

    for cell in raw_data {
        if cell.is_empty() || cell.to_lowercase() == "na" {
            result.push(None);
        } else {
            match cell.to_lowercase().as_str() {
                "true" | "1" | "yes" => result.push(Some(true)),
                "false" | "0" | "no" => result.push(Some(false)),
                _ => return None, // If ANY value fails, not a boolean column
            }
        }
    }
    Some(result)
}

impl From<Vec<i64>> for Box<dyn ColumnArray> {
    fn from(data: Vec<i64>) -> Self {
        let data: Vec<Option<i64>> = data.into_iter().map(Some).collect();
        Box::new(IntegerColumn(data))
    }
}

// Vec<Option<i64>> -> IntegerColumn
impl From<Vec<Option<i64>>> for Box<dyn ColumnArray> {
    fn from(data: Vec<Option<i64>>) -> Self {
        Box::new(IntegerColumn(data))
    }
}

// Vec<f64> -> FloatColumn
impl From<Vec<f64>> for Box<dyn ColumnArray> {
    fn from(data: Vec<f64>) -> Self {
        let data: Vec<Option<f64>> = data.into_iter().map(Some).collect();
        Box::new(FloatColumn(data))
    }
}

impl From<Vec<String>> for Box<dyn ColumnArray> {
    fn from(data: Vec<String>) -> Self {
        let data: Vec<Option<String>> = data.into_iter().map(Some).collect();
        Box::new(StringColumn(data))
    }
}

impl From<&[i64]> for Box<dyn ColumnArray> {
    fn from(data: &[i64]) -> Self {
        Vec::from(data).into()
    }
}

impl From<Vec<Option<f64>>> for Box<dyn ColumnArray> {
    fn from(data: Vec<Option<f64>>) -> Self {
        Box::new(FloatColumn(data))
    }
}

impl From<Vec<Option<String>>> for Box<dyn ColumnArray> {
    fn from(data: Vec<Option<String>>) -> Self {
        Box::new(StringColumn(data))
    }
}

// Vec<bool> -> BooleanColumn
impl From<Vec<bool>> for Box<dyn ColumnArray> {
    fn from(data: Vec<bool>) -> Self {
        let data: Vec<Option<bool>> = data.into_iter().map(Some).collect();
        Box::new(BooleanColumn(data))
    }
}

// Vec<Option<bool>> -> BooleanColumn
impl From<Vec<Option<bool>>> for Box<dyn ColumnArray> {
    fn from(data: Vec<Option<bool>>) -> Self {
        Box::new(BooleanColumn(data))
    }
}

impl From<Vec<usize>> for Box<dyn ColumnArray> {
    fn from(data: Vec<usize>) -> Self {
        let input = data.iter().map(|&x| Some(x as i64)).collect();
        Box::new(IntegerColumn(input))
    }
}