forked from pola-rs/polars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataframe.rs
731 lines (641 loc) · 22 KB
/
dataframe.rs
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
use polars::prelude::*;
use pyo3::{exceptions::PyRuntimeError, prelude::*};
use crate::conversion::Wrap;
use crate::datatypes::PyDataType;
use crate::file::FileLike;
use crate::lazy::dataframe::PyLazyFrame;
use crate::utils::str_to_polarstype;
use crate::{
arrow_interop,
error::PyPolarsEr,
file::{get_either_file, get_file_like, EitherRustPythonFile},
series::{to_pyseries_collection, to_series_collection, PySeries},
};
use polars::frame::{group_by::GroupBy, resample::SampleRule};
use pyo3::types::PyTuple;
use std::convert::TryFrom;
#[pyclass]
#[repr(transparent)]
#[derive(Clone)]
pub struct PyDataFrame {
pub df: DataFrame,
}
impl PyDataFrame {
pub(crate) fn new(df: DataFrame) -> Self {
PyDataFrame { df }
}
}
impl From<DataFrame> for PyDataFrame {
fn from(df: DataFrame) -> Self {
PyDataFrame { df }
}
}
#[pymethods]
#[allow(
clippy::wrong_self_convention,
clippy::should_implement_trait,
clippy::len_without_is_empty
)]
impl PyDataFrame {
#[new]
pub fn __init__(columns: Vec<PySeries>) -> PyResult<Self> {
let columns = to_series_collection(columns);
let df = DataFrame::new(columns).map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
#[staticmethod]
#[allow(clippy::too_many_arguments)]
pub fn read_csv(
py_f: PyObject,
infer_schema_length: usize,
batch_size: usize,
has_header: bool,
ignore_errors: bool,
stop_after_n_rows: Option<usize>,
skip_rows: usize,
projection: Option<Vec<usize>>,
sep: &str,
rechunk: bool,
columns: Option<Vec<String>>,
encoding: &str,
mut n_threads: Option<usize>,
path: Option<String>,
overwrite_dtype: Option<Vec<(&str, &PyAny)>>,
) -> PyResult<Self> {
let encoding = match encoding {
"utf8" => CsvEncoding::Utf8,
"utf8-lossy" => CsvEncoding::LossyUtf8,
e => {
return Err(
PyPolarsEr::Other(format!("encoding not {} not implemented.", e)).into(),
)
}
};
let overwrite_dtype = overwrite_dtype.map(|overwrite_dtype| {
let fields = overwrite_dtype
.iter()
.map(|(name, dtype)| {
let str_repr = dtype.str().unwrap().to_str().unwrap();
let dtype = str_to_polarstype(str_repr);
Field::new(name, dtype)
})
.collect();
Schema::new(fields)
});
let file = get_either_file(py_f, false)?;
// Python files cannot be send to another thread.
let file: Box<dyn FileLike> = match file {
EitherRustPythonFile::Py(f) => {
n_threads = Some(1);
Box::new(f)
}
EitherRustPythonFile::Rust(f) => Box::new(f),
};
let df = CsvReader::new(file)
.infer_schema(Some(infer_schema_length))
.has_header(has_header)
.with_stop_after_n_rows(stop_after_n_rows)
.with_delimiter(sep.as_bytes()[0])
.with_skip_rows(skip_rows)
.with_ignore_parser_errors(ignore_errors)
.with_projection(projection)
.with_rechunk(rechunk)
.with_batch_size(batch_size)
.with_encoding(encoding)
.with_columns(columns)
.with_n_threads(n_threads)
.with_path(path)
.with_dtype_overwrite(overwrite_dtype.as_ref())
.finish()
.map_err(PyPolarsEr::from)?;
Ok(df.into())
}
#[staticmethod]
pub fn read_parquet(py_f: PyObject, stop_after_n_rows: Option<usize>) -> PyResult<Self> {
use EitherRustPythonFile::*;
let result = match get_either_file(py_f, false)? {
Py(f) => {
let buf = f.as_slicable_buffer();
ParquetReader::new(buf)
.with_stop_after_n_rows(stop_after_n_rows)
.finish()
}
Rust(f) => ParquetReader::new(f)
.with_stop_after_n_rows(stop_after_n_rows)
.finish(),
};
let df = result.map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
#[staticmethod]
pub fn read_ipc(py_f: PyObject) -> PyResult<Self> {
let file = get_file_like(py_f, false)?;
let df = IpcReader::new(file).finish().map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
#[staticmethod]
pub fn from_arrow_record_batches(rb: Vec<&PyAny>) -> PyResult<Self> {
let batches = arrow_interop::to_rust::to_rust_rb(&rb)?;
let df = DataFrame::try_from(batches).map_err(PyPolarsEr::from)?;
Ok(Self::from(df))
}
pub fn to_csv(
&mut self,
py_f: PyObject,
batch_size: usize,
has_headers: bool,
delimiter: u8,
) -> PyResult<()> {
let mut buf = get_file_like(py_f, true)?;
CsvWriter::new(&mut buf)
.has_headers(has_headers)
.with_delimiter(delimiter)
.with_batch_size(batch_size)
.finish(&mut self.df)
.map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn to_ipc(&mut self, py_f: PyObject) -> PyResult<()> {
let mut buf = get_file_like(py_f, true)?;
IpcWriter::new(&mut buf)
.finish(&mut self.df)
.map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn row_tuple(&self, idx: i64) -> PyObject {
let gil = Python::acquire_gil();
let py = gil.python();
let idx = if idx < 0 {
(self.df.height() as i64 + idx) as usize
} else {
idx as usize
};
PyTuple::new(
py,
self.df
.get_columns()
.iter()
.map(|s| Wrap(s.get(idx)).into_py(py)),
)
.into_py(py)
}
pub fn to_parquet(&mut self, path: &str) -> PyResult<()> {
let f = std::fs::File::create(path).expect("to open a new file");
ParquetWriter::new(f)
.finish(&mut self.df)
.map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn to_arrow(&self) -> PyResult<Vec<PyObject>> {
let gil = Python::acquire_gil();
let py = gil.python();
let pyarrow = py.import("pyarrow")?;
let rbs = self
.df
.as_record_batches()
.map_err(PyPolarsEr::from)?
.iter()
.map(|rb| arrow_interop::to_py::to_py_rb(rb, py, pyarrow))
.collect::<PyResult<_>>()?;
Ok(rbs)
}
pub fn add(&self, s: &PySeries) -> PyResult<Self> {
let df = (&self.df + &s.series).map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn sub(&self, s: &PySeries) -> PyResult<Self> {
let df = (&self.df - &s.series).map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn div(&self, s: &PySeries) -> PyResult<Self> {
let df = (&self.df / &s.series).map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn mul(&self, s: &PySeries) -> PyResult<Self> {
let df = (&self.df * &s.series).map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn rem(&self, s: &PySeries) -> PyResult<Self> {
let df = (&self.df % &s.series).map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn sample_n(&self, n: usize, with_replacement: bool) -> PyResult<Self> {
let df = self
.df
.sample_n(n, with_replacement)
.map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn sample_frac(&self, frac: f64, with_replacement: bool) -> PyResult<Self> {
let df = self
.df
.sample_frac(frac, with_replacement)
.map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn rechunk(&mut self) -> Self {
self.df.agg_chunks().into()
}
/// Format `DataFrame` as String
pub fn as_str(&self) -> String {
format!("{:?}", self.df)
}
pub fn fill_none(&self, strategy: &str) -> PyResult<Self> {
let strat = match strategy {
"backward" => FillNoneStrategy::Backward,
"forward" => FillNoneStrategy::Forward,
"min" => FillNoneStrategy::Min,
"max" => FillNoneStrategy::Max,
"mean" => FillNoneStrategy::Mean,
s => return Err(PyPolarsEr::Other(format!("Strategy {} not supported", s)).into()),
};
let df = self.df.fill_none(strat).map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn join(
&self,
other: &PyDataFrame,
left_on: Vec<&str>,
right_on: Vec<&str>,
how: &str,
) -> PyResult<Self> {
let how = match how {
"left" => JoinType::Left,
"inner" => JoinType::Inner,
"outer" => JoinType::Outer,
_ => panic!("not supported"),
};
let df = self
.df
.join(&other.df, left_on, right_on, how)
.map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn get_columns(&self) -> Vec<PySeries> {
let cols = self.df.get_columns().clone();
to_pyseries_collection(cols)
}
/// Get column names
pub fn columns(&self) -> Vec<&str> {
self.df.get_column_names()
}
/// set column names
pub fn set_column_names(&mut self, names: Vec<&str>) -> PyResult<()> {
self.df.set_column_names(&names).map_err(PyPolarsEr::from)?;
Ok(())
}
/// Get datatypes
pub fn dtypes(&self) -> Vec<u8> {
self.df
.dtypes()
.iter()
.map(|arrow_dtype| {
let dt: PyDataType = arrow_dtype.into();
dt as u8
})
.collect()
}
pub fn n_chunks(&self) -> PyResult<usize> {
let n = self.df.n_chunks().map_err(PyPolarsEr::from)?;
Ok(n)
}
pub fn shape(&self) -> (usize, usize) {
self.df.shape()
}
pub fn height(&self) -> usize {
self.df.height()
}
pub fn width(&self) -> usize {
self.df.width()
}
pub fn hstack_mut(&mut self, columns: Vec<PySeries>) -> PyResult<()> {
let columns = to_series_collection(columns);
self.df.hstack_mut(&columns).map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn hstack(&self, columns: Vec<PySeries>) -> PyResult<Self> {
let columns = to_series_collection(columns);
let df = self.df.hstack(&columns).map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn vstack_mut(&mut self, df: &PyDataFrame) -> PyResult<()> {
self.df.vstack_mut(&df.df).map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn vstack(&mut self, df: &PyDataFrame) -> PyResult<Self> {
let df = self.df.vstack(&df.df).map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn drop_in_place(&mut self, name: &str) -> PyResult<PySeries> {
let s = self.df.drop_in_place(name).map_err(PyPolarsEr::from)?;
Ok(PySeries { series: s })
}
pub fn drop_nulls(&self, subset: Option<Vec<String>>) -> PyResult<Self> {
let df = self
.df
.drop_nulls(subset.as_ref().map(|s| s.as_ref()))
.map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn drop(&self, name: &str) -> PyResult<Self> {
let df = self.df.drop(name).map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn select_at_idx(&self, idx: usize) -> Option<PySeries> {
self.df.select_at_idx(idx).map(|s| PySeries::new(s.clone()))
}
pub fn find_idx_by_name(&self, name: &str) -> Option<usize> {
self.df.find_idx_by_name(name)
}
pub fn column(&self, name: &str) -> PyResult<PySeries> {
let series = self
.df
.column(name)
.map(|s| PySeries::new(s.clone()))
.map_err(PyPolarsEr::from)?;
Ok(series)
}
pub fn select(&self, selection: Vec<&str>) -> PyResult<Self> {
let df = self.df.select(&selection).map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn filter(&self, mask: &PySeries) -> PyResult<Self> {
let filter_series = &mask.series;
if let Ok(ca) = filter_series.bool() {
let df = self.df.filter(ca).map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
} else {
Err(PyRuntimeError::new_err("Expected a boolean mask"))
}
}
pub fn take(&self, indices: Vec<usize>) -> Self {
let df = self.df.take_iter(indices.iter().copied());
PyDataFrame::new(df)
}
pub fn take_with_series(&self, indices: &PySeries) -> PyResult<Self> {
let idx = indices.series.u32().map_err(PyPolarsEr::from)?;
let df = self.df.take(&idx);
Ok(PyDataFrame::new(df))
}
pub fn sort(&self, by_column: &str, reverse: bool) -> PyResult<Self> {
let df = self.df.sort(by_column, reverse).map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn sort_in_place(&mut self, by_column: &str, reverse: bool) -> PyResult<()> {
self.df
.sort_in_place(by_column, reverse)
.map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn replace(&mut self, column: &str, new_col: PySeries) -> PyResult<()> {
self.df
.replace(column, new_col.series)
.map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn replace_at_idx(&mut self, index: usize, new_col: PySeries) -> PyResult<()> {
self.df
.replace_at_idx(index, new_col.series)
.map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn insert_at_idx(&mut self, index: usize, new_col: PySeries) -> PyResult<()> {
self.df
.insert_at_idx(index, new_col.series)
.map_err(PyPolarsEr::from)?;
Ok(())
}
pub fn slice(&self, offset: usize, length: usize) -> PyResult<Self> {
let df = self.df.slice(offset as i64, length).map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn head(&self, length: Option<usize>) -> Self {
let df = self.df.head(length);
PyDataFrame::new(df)
}
pub fn tail(&self, length: Option<usize>) -> Self {
let df = self.df.tail(length);
PyDataFrame::new(df)
}
pub fn is_unique(&self) -> PyResult<PySeries> {
let mask = self.df.is_unique().map_err(PyPolarsEr::from)?;
Ok(mask.into_series().into())
}
pub fn is_duplicated(&self) -> PyResult<PySeries> {
let mask = self.df.is_unique().map_err(PyPolarsEr::from)?;
Ok(mask.into_series().into())
}
pub fn frame_equal(&self, other: &PyDataFrame, null_equal: bool) -> bool {
if null_equal {
self.df.frame_equal_missing(&other.df)
} else {
self.df.frame_equal(&other.df)
}
}
pub fn downsample_agg(
&self,
by: &str,
rule: &str,
n: u32,
column_to_agg: Vec<(&str, Vec<&str>)>,
) -> PyResult<Self> {
let rule = match rule {
"second" => SampleRule::Second(n),
"minute" => SampleRule::Minute(n),
"day" => SampleRule::Day(n),
"hour" => SampleRule::Hour(n),
a => {
return Err(PyPolarsEr::Other(format!("rule {} not supported", a)).into());
}
};
let gb = self.df.downsample(by, rule).map_err(PyPolarsEr::from)?;
let df = gb.agg(&column_to_agg).map_err(PyPolarsEr::from)?;
let out = df.sort(by, false).map_err(PyPolarsEr::from)?;
Ok(out.into())
}
pub fn downsample(&self, by: &str, rule: &str, n: u32, agg: &str) -> PyResult<Self> {
let rule = match rule {
"second" => SampleRule::Second(n),
"minute" => SampleRule::Minute(n),
"day" => SampleRule::Day(n),
"hour" => SampleRule::Hour(n),
a => {
return Err(PyPolarsEr::Other(format!("rule {} not supported", a)).into());
}
};
let gb = self.df.downsample(by, rule).map_err(PyPolarsEr::from)?;
let df = finish_groupby(gb, agg)?;
let out = df.df.sort(by, false).map_err(PyPolarsEr::from)?;
Ok(out.into())
}
pub fn groupby(&self, by: Vec<&str>, select: Option<Vec<String>>, agg: &str) -> PyResult<Self> {
let gb = self.df.groupby(&by).map_err(PyPolarsEr::from)?;
let selection = match select.as_ref() {
Some(s) => gb.select(s),
None => gb,
};
finish_groupby(selection, agg)
}
pub fn groupby_agg(
&self,
by: Vec<&str>,
column_to_agg: Vec<(&str, Vec<&str>)>,
) -> PyResult<Self> {
let gb = self.df.groupby(&by).map_err(PyPolarsEr::from)?;
let df = gb.agg(&column_to_agg).map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn groupby_apply(&self, by: Vec<&str>, lambda: PyObject) -> PyResult<Self> {
let gb = self.df.groupby(&by).map_err(PyPolarsEr::from)?;
let function = move |df: DataFrame| {
let gil = Python::acquire_gil();
let py = gil.python();
// get the pypolars module
let pypolars = PyModule::import(py, "polars").unwrap();
// create a PyDataFrame struct/object for Python
let pydf = PyDataFrame::new(df);
// Wrap this PySeries object in the python side DataFrame wrapper
let python_df_wrapper = pypolars.call1("wrap_df", (pydf,)).unwrap();
// call the lambda and get a python side DataFrame wrapper
let result_df_wrapper = match lambda.call1(py, (python_df_wrapper,)) {
Ok(pyobj) => pyobj,
Err(e) => panic!("UDF failed: {}", e.pvalue(py).to_string()),
};
// unpack the wrapper in a PyDataFrame
let py_pydf = result_df_wrapper.getattr(py, "_df").expect(
"Could net get DataFrame attribute '_df'. Make sure that you return a DataFrame object.",
);
// Downcast to Rust
let pydf = py_pydf.extract::<PyDataFrame>(py).unwrap();
// Finally get the actual DataFrame
Ok(pydf.df)
};
let gil = Python::acquire_gil();
let py = gil.python();
let df = py.allow_threads(|| gb.apply(function).map_err(PyPolarsEr::from))?;
Ok(df.into())
}
pub fn groupby_quantile(
&self,
by: Vec<&str>,
select: Vec<String>,
quantile: f64,
) -> PyResult<Self> {
let gb = self.df.groupby(&by).map_err(PyPolarsEr::from)?;
let selection = gb.select(&select);
let df = selection.quantile(quantile);
let df = df.map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn pivot(
&self,
by: Vec<String>,
pivot_column: &str,
values_column: &str,
agg: &str,
) -> PyResult<Self> {
let mut gb = self.df.groupby(&by).map_err(PyPolarsEr::from)?;
let pivot = gb.pivot(pivot_column, values_column);
let df = match agg {
"first" => pivot.first(),
"min" => pivot.min(),
"max" => pivot.max(),
"mean" => pivot.mean(),
"median" => pivot.median(),
"sum" => pivot.sum(),
"count" => pivot.count(),
a => Err(PolarsError::Other(
format!("agg fn {} does not exists", a).into(),
)),
};
let df = df.map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn clone(&self) -> Self {
PyDataFrame::new(self.df.clone())
}
pub fn explode(&self, columns: Vec<String>) -> PyResult<Self> {
let df = self.df.explode(&columns);
let df = df.map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn melt(&self, id_vars: Vec<&str>, value_vars: Vec<&str>) -> PyResult<Self> {
let df = self
.df
.melt(id_vars, value_vars)
.map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}
pub fn shift(&self, periods: i64) -> Self {
self.df.shift(periods).into()
}
pub fn drop_duplicates(
&self,
maintain_order: bool,
subset: Option<Vec<String>>,
) -> PyResult<Self> {
let df = self
.df
.drop_duplicates(maintain_order, subset.as_ref().map(|v| v.as_ref()))
.map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn lazy(&self) -> PyLazyFrame {
self.df.clone().lazy().into()
}
pub fn max(&self) -> Self {
self.df.max().into()
}
pub fn min(&self) -> Self {
self.df.min().into()
}
pub fn sum(&self) -> Self {
self.df.sum().into()
}
pub fn mean(&self) -> Self {
self.df.mean().into()
}
pub fn std(&self) -> Self {
self.df.std().into()
}
pub fn var(&self) -> Self {
self.df.var().into()
}
pub fn median(&self) -> Self {
self.df.median().into()
}
pub fn quantile(&self, quantile: f64) -> PyResult<Self> {
let df = self.df.quantile(quantile).map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn to_dummies(&self) -> PyResult<Self> {
let df = self.df.to_dummies().map_err(PyPolarsEr::from)?;
Ok(df.into())
}
pub fn null_count(&self) -> Self {
let df = self.df.null_count();
df.into()
}
}
fn finish_groupby(gb: GroupBy, agg: &str) -> PyResult<PyDataFrame> {
let df = match agg {
"min" => gb.min(),
"max" => gb.max(),
"mean" => gb.mean(),
"first" => gb.first(),
"last" => gb.last(),
"sum" => gb.sum(),
"count" => gb.count(),
"n_unique" => gb.n_unique(),
"median" => gb.median(),
"agg_list" => gb.agg_list(),
"groups" => gb.groups(),
"std" => gb.std(),
"var" => gb.var(),
a => Err(PolarsError::Other(
format!("agg fn {} does not exists", a).into(),
)),
};
let df = df.map_err(PyPolarsEr::from)?;
Ok(PyDataFrame::new(df))
}