pandrs 0.4.1

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
//! Arrow RecordBatch -> DataFrame value conversion (per-cell, never per-array).

use crate::dataframe::DataFrame;
use crate::error::{Error, Result};
use crate::series::Series;
use arrow::array::{
    Array, BooleanArray, Date32Array, Date64Array, Decimal128Array, Decimal256Array,
    LargeStringArray, PrimitiveArray, StringArray, UInt64Array,
};
use arrow::datatypes::{
    ArrowPrimitiveType, DataType, Float32Type, Float64Type, Int16Type, Int32Type, Int64Type,
    Int8Type, SchemaRef, TimeUnit, TimestampMicrosecondType, TimestampMillisecondType,
    TimestampNanosecondType, TimestampSecondType, UInt16Type, UInt32Type, UInt8Type,
};
use arrow::record_batch::RecordBatch;

/// Collect one Arrow primitive column whose native type widens losslessly
/// into `i64` — every signed/unsigned integer width up to 32 bits, plus i64
/// itself — into a native `Vec<i64>`. This is how Parquet-native Int8/16/32
/// and UInt8/16/32 columns (which pandas/pyarrow write by default, but
/// pandrs itself never does) become real, typed pandrs columns instead of
/// falling into a fallback that used to format the *entire array* as the
/// text of every single cell.
pub(super) fn collect_i64_column<T>(
    batches: &[RecordBatch],
    col_idx: usize,
    col_name: &str,
) -> Result<Vec<i64>>
where
    T: ArrowPrimitiveType,
    T::Native: Into<i64>,
{
    let mut values = Vec::new();
    for batch in batches {
        let array = batch
            .column(col_idx)
            .as_any()
            .downcast_ref::<PrimitiveArray<T>>()
            .ok_or_else(|| {
                Error::Cast(format!(
                    "Failed to cast column '{}' to a primitive integer array",
                    col_name
                ))
            })?;
        for i in 0..array.len() {
            values.push(if array.is_null(i) {
                0
            } else {
                array.value(i).into()
            });
        }
    }
    Ok(values)
}

/// Collect a UInt64 column as `i64`, saturating at `i64::MAX` for values
/// that don't fit. pandrs has no native unsigned column type, and a plain
/// `as i64` cast would wrap out-of-range values to negative numbers, which
/// is a worse corruption than clamping to the largest representable value.
pub(super) fn collect_u64_saturating_column(
    batches: &[RecordBatch],
    col_idx: usize,
    col_name: &str,
) -> Result<Vec<i64>> {
    let mut values = Vec::new();
    for batch in batches {
        let array = batch
            .column(col_idx)
            .as_any()
            .downcast_ref::<UInt64Array>()
            .ok_or_else(|| {
                Error::Cast(format!(
                    "Failed to cast column '{}' to UInt64Array",
                    col_name
                ))
            })?;
        for i in 0..array.len() {
            values.push(if array.is_null(i) {
                0
            } else {
                i64::try_from(array.value(i)).unwrap_or(i64::MAX)
            });
        }
    }
    Ok(values)
}

/// Collect one Arrow primitive column whose native type widens losslessly
/// into `f64` (Float32, Float64) into a native `Vec<f64>`.
pub(super) fn collect_f64_column<T>(
    batches: &[RecordBatch],
    col_idx: usize,
    col_name: &str,
) -> Result<Vec<f64>>
where
    T: ArrowPrimitiveType,
    T::Native: Into<f64>,
{
    let mut values = Vec::new();
    for batch in batches {
        let array = batch
            .column(col_idx)
            .as_any()
            .downcast_ref::<PrimitiveArray<T>>()
            .ok_or_else(|| {
                Error::Cast(format!(
                    "Failed to cast column '{}' to a primitive float array",
                    col_name
                ))
            })?;
        for i in 0..array.len() {
            values.push(if array.is_null(i) {
                f64::NAN
            } else {
                array.value(i).into()
            });
        }
    }
    Ok(values)
}

/// Collect one Arrow timestamp column — whose native representation is
/// always `i64` regardless of time unit — into datetime strings via
/// `format`, which already encodes the unit (seconds/millis/micros/nanos).
pub(super) fn collect_timestamp_column<T>(
    batches: &[RecordBatch],
    col_idx: usize,
    col_name: &str,
    format: impl Fn(i64) -> String,
) -> Result<Vec<String>>
where
    T: ArrowPrimitiveType<Native = i64>,
{
    let mut values = Vec::new();
    for batch in batches {
        let array = batch
            .column(col_idx)
            .as_any()
            .downcast_ref::<PrimitiveArray<T>>()
            .ok_or_else(|| {
                Error::Cast(format!(
                    "Failed to cast column '{}' to a timestamp array",
                    col_name
                ))
            })?;
        for i in 0..array.len() {
            values.push(if array.is_null(i) {
                "1970-01-01T00:00:00".to_string()
            } else {
                format(array.value(i))
            });
        }
    }
    Ok(values)
}

/// Format a DATE32 value (days since the Unix epoch) as an ISO-8601 date.
pub(super) fn format_date32(days: i32) -> String {
    match chrono::DateTime::from_timestamp(days as i64 * 86_400, 0) {
        Some(dt) => dt.format("%Y-%m-%d").to_string(),
        None => format!("invalid-date32({days})"),
    }
}

/// Format a DATE64 value (milliseconds since the Unix epoch, per the Arrow
/// spec) as an ISO-8601 date.
pub(super) fn format_date64(millis: i64) -> String {
    match chrono::DateTime::from_timestamp_millis(millis) {
        Some(dt) => dt.format("%Y-%m-%d").to_string(),
        None => format!("invalid-date64({millis})"),
    }
}

pub(super) fn format_timestamp_seconds(secs: i64) -> String {
    match chrono::DateTime::from_timestamp(secs, 0) {
        Some(dt) => dt.format("%Y-%m-%d %H:%M:%S").to_string(),
        None => format!("invalid-timestamp({secs})"),
    }
}

pub(super) fn format_timestamp_millis(millis: i64) -> String {
    match chrono::DateTime::from_timestamp_millis(millis) {
        Some(dt) => dt.format("%Y-%m-%d %H:%M:%S%.3f").to_string(),
        None => format!("invalid-timestamp({millis})"),
    }
}

pub(super) fn format_timestamp_micros(micros: i64) -> String {
    match chrono::DateTime::from_timestamp_micros(micros) {
        Some(dt) => dt.format("%Y-%m-%d %H:%M:%S%.6f").to_string(),
        None => format!("invalid-timestamp({micros})"),
    }
}

pub(super) fn format_timestamp_nanos(nanos: i64) -> String {
    chrono::DateTime::from_timestamp_nanos(nanos)
        .format("%Y-%m-%d %H:%M:%S%.9f")
        .to_string()
}

/// Build a `Series<T>` from already-collected values and add it to `df`.
pub(super) fn push_column<T: 'static + std::fmt::Debug + Clone + Send + Sync>(
    df: &mut DataFrame,
    col_name: &str,
    values: Vec<T>,
) -> Result<()> {
    let series = Series::new(values, Some(col_name.to_string()))?;
    df.add_column(col_name.to_string(), series)
}

/// Convert Arrow record batches to a DataFrame.
///
/// Every numeric width Arrow actually produces for Parquet files written by
/// other tools (pandas/pyarrow defaults include Int32, Float32 and various
/// unsigned/decimal/date64 columns that pandrs itself never writes but must
/// still be able to read) is converted through `array.value(i)` into a real,
/// natively-typed pandrs column — never by formatting a whole Arrow array as
/// the "value" of a single cell, which used to both corrupt every cell of
/// such a column and make the read `O(rows^2)`.
pub(super) fn record_batches_to_dataframe(
    batches: &[RecordBatch],
    schema: SchemaRef,
) -> Result<DataFrame> {
    let mut df = DataFrame::new();

    for (col_idx, field) in schema.fields().iter().enumerate() {
        let col_name = field.name().as_str();

        match field.data_type() {
            DataType::Int8 => {
                let values = collect_i64_column::<Int8Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Int16 => {
                let values = collect_i64_column::<Int16Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Int32 => {
                let values = collect_i64_column::<Int32Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Int64 => {
                let values = collect_i64_column::<Int64Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::UInt8 => {
                let values = collect_i64_column::<UInt8Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::UInt16 => {
                let values = collect_i64_column::<UInt16Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::UInt32 => {
                let values = collect_i64_column::<UInt32Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::UInt64 => {
                let values = collect_u64_saturating_column(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Float32 => {
                let values = collect_f64_column::<Float32Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Float64 => {
                let values = collect_f64_column::<Float64Type>(batches, col_idx, col_name)?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Boolean => {
                let mut values = Vec::new();
                for batch in batches {
                    let array = batch
                        .column(col_idx)
                        .as_any()
                        .downcast_ref::<BooleanArray>()
                        .ok_or_else(|| {
                            Error::Cast(format!(
                                "Failed to cast column '{}' to BooleanArray",
                                col_name
                            ))
                        })?;
                    for i in 0..array.len() {
                        values.push(!array.is_null(i) && array.value(i));
                    }
                }
                push_column(&mut df, col_name, values)?;
            }
            DataType::Utf8 => {
                let mut values = Vec::new();
                for batch in batches {
                    let array = batch
                        .column(col_idx)
                        .as_any()
                        .downcast_ref::<StringArray>()
                        .ok_or_else(|| {
                            Error::Cast(format!(
                                "Failed to cast column '{}' to StringArray",
                                col_name
                            ))
                        })?;
                    for i in 0..array.len() {
                        values.push(if array.is_null(i) {
                            String::new()
                        } else {
                            array.value(i).to_string()
                        });
                    }
                }
                push_column(&mut df, col_name, values)?;
            }
            DataType::LargeUtf8 => {
                // `LargeUtf8` is `GenericStringArray<i64>` (`LargeStringArray`),
                // a distinct Rust type from `StringArray`
                // (`GenericStringArray<i32>`, for plain `Utf8`); downcasting a
                // LargeUtf8 column to `StringArray` always returned `None`,
                // turning every large-string column into a cast error.
                let mut values = Vec::new();
                for batch in batches {
                    let array = batch
                        .column(col_idx)
                        .as_any()
                        .downcast_ref::<LargeStringArray>()
                        .ok_or_else(|| {
                            Error::Cast(format!(
                                "Failed to cast column '{}' to LargeStringArray",
                                col_name
                            ))
                        })?;
                    for i in 0..array.len() {
                        values.push(if array.is_null(i) {
                            String::new()
                        } else {
                            array.value(i).to_string()
                        });
                    }
                }
                push_column(&mut df, col_name, values)?;
            }
            DataType::Date32 => {
                let mut values = Vec::new();
                for batch in batches {
                    let array = batch
                        .column(col_idx)
                        .as_any()
                        .downcast_ref::<Date32Array>()
                        .ok_or_else(|| {
                            Error::Cast(format!(
                                "Failed to cast column '{}' to Date32Array",
                                col_name
                            ))
                        })?;
                    for i in 0..array.len() {
                        values.push(if array.is_null(i) {
                            "1970-01-01".to_string()
                        } else {
                            format_date32(array.value(i))
                        });
                    }
                }
                push_column(&mut df, col_name, values)?;
            }
            DataType::Date64 => {
                let mut values = Vec::new();
                for batch in batches {
                    let array = batch
                        .column(col_idx)
                        .as_any()
                        .downcast_ref::<Date64Array>()
                        .ok_or_else(|| {
                            Error::Cast(format!(
                                "Failed to cast column '{}' to Date64Array",
                                col_name
                            ))
                        })?;
                    for i in 0..array.len() {
                        values.push(if array.is_null(i) {
                            "1970-01-01".to_string()
                        } else {
                            format_date64(array.value(i))
                        });
                    }
                }
                push_column(&mut df, col_name, values)?;
            }
            DataType::Timestamp(TimeUnit::Second, _) => {
                let values = collect_timestamp_column::<TimestampSecondType>(
                    batches,
                    col_idx,
                    col_name,
                    format_timestamp_seconds,
                )?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Timestamp(TimeUnit::Millisecond, _) => {
                let values = collect_timestamp_column::<TimestampMillisecondType>(
                    batches,
                    col_idx,
                    col_name,
                    format_timestamp_millis,
                )?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Timestamp(TimeUnit::Microsecond, _) => {
                let values = collect_timestamp_column::<TimestampMicrosecondType>(
                    batches,
                    col_idx,
                    col_name,
                    format_timestamp_micros,
                )?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Timestamp(TimeUnit::Nanosecond, _) => {
                let values = collect_timestamp_column::<TimestampNanosecondType>(
                    batches,
                    col_idx,
                    col_name,
                    format_timestamp_nanos,
                )?;
                push_column(&mut df, col_name, values)?;
            }
            DataType::Decimal128(_, scale) => {
                let scale = *scale;
                let mut values = Vec::new();
                for batch in batches {
                    let array = batch
                        .column(col_idx)
                        .as_any()
                        .downcast_ref::<Decimal128Array>()
                        .ok_or_else(|| {
                            Error::Cast(format!(
                                "Failed to cast column '{}' to Decimal128Array",
                                col_name
                            ))
                        })?;
                    for i in 0..array.len() {
                        values.push(if array.is_null(i) {
                            f64::NAN
                        } else {
                            array.value(i) as f64 / 10f64.powi(scale as i32)
                        });
                    }
                }
                push_column(&mut df, col_name, values)?;
            }
            DataType::Decimal256(_, scale) => {
                let scale = *scale;
                let mut values = Vec::new();
                for batch in batches {
                    let array = batch
                        .column(col_idx)
                        .as_any()
                        .downcast_ref::<Decimal256Array>()
                        .ok_or_else(|| {
                            Error::Cast(format!(
                                "Failed to cast column '{}' to Decimal256Array",
                                col_name
                            ))
                        })?;
                    for i in 0..array.len() {
                        if array.is_null(i) {
                            values.push(f64::NAN);
                            continue;
                        }
                        let raw = array.value(i);
                        let base = raw
                            .to_i128()
                            .map(|v| v as f64)
                            .unwrap_or_else(|| raw.to_string().parse::<f64>().unwrap_or(f64::NAN));
                        values.push(base / 10f64.powi(scale as i32));
                    }
                }
                push_column(&mut df, col_name, values)?;
            }
            other => {
                return Err(Error::NotImplemented(format!(
                    "Reading Parquet column '{}' with Arrow type {:?} is not yet supported",
                    col_name, other
                )));
            }
        }
    }

    Ok(df)
}