-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
mod.rs
3264 lines (3012 loc) · 109 KB
/
mod.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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! DataFrame module.
use std::borrow::Cow;
use std::iter::{FromIterator, Iterator};
use std::{mem, ops};
use ahash::AHashSet;
use rayon::prelude::*;
#[cfg(feature = "algorithm_group_by")]
use crate::chunked_array::ops::unique::is_unique_helper;
use crate::prelude::*;
use crate::utils::{slice_offsets, split_ca, split_df, try_get_supertype, NoNull};
#[cfg(feature = "dataframe_arithmetic")]
mod arithmetic;
mod chunks;
pub mod explode;
mod from;
#[cfg(feature = "algorithm_group_by")]
pub mod group_by;
#[cfg(feature = "rows")]
pub mod row;
mod top_k;
mod upstream_traits;
pub use chunks::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use smartstring::alias::String as SmartString;
#[cfg(feature = "algorithm_group_by")]
use crate::frame::group_by::GroupsIndicator;
#[cfg(feature = "row_hash")]
use crate::hashing::_df_rows_to_hashes_threaded_vertical;
#[cfg(feature = "zip_with")]
use crate::prelude::min_max_binary::min_max_binary_series;
use crate::prelude::sort::{argsort_multiple_row_fmt, prepare_arg_sort};
use crate::series::IsSorted;
use crate::POOL;
#[derive(Copy, Clone, Debug)]
pub enum NullStrategy {
Ignore,
Propagate,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum UniqueKeepStrategy {
/// Keep the first unique row.
First,
/// Keep the last unique row.
Last,
/// Keep None of the unique rows.
None,
/// Keep any of the unique rows
/// This allows more optimizations
#[default]
Any,
}
/// A contiguous growable collection of `Series` that have the same length.
///
/// ## Use declarations
///
/// All the common tools can be found in [`crate::prelude`] (or in `polars::prelude`).
///
/// ```rust
/// use polars_core::prelude::*; // if the crate polars-core is used directly
/// // use polars::prelude::*; if the crate polars is used
/// ```
///
/// # Initialization
/// ## Default
///
/// A `DataFrame` can be initialized empty:
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df = DataFrame::default();
/// assert!(df.is_empty());
/// ```
///
/// ## Wrapping a `Vec<Series>`
///
/// A `DataFrame` is built upon a `Vec<Series>` where the `Series` have the same length.
///
/// ```rust
/// # use polars_core::prelude::*;
/// let s1 = Series::new("Fruit", &["Apple", "Apple", "Pear"]);
/// let s2 = Series::new("Color", &["Red", "Yellow", "Green"]);
///
/// let df: PolarsResult<DataFrame> = DataFrame::new(vec![s1, s2]);
/// ```
///
/// ## Using a macro
///
/// The [`df!`] macro is a convenient method:
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: PolarsResult<DataFrame> = df!("Fruit" => &["Apple", "Apple", "Pear"],
/// "Color" => &["Red", "Yellow", "Green"]);
/// ```
///
/// ## Using a CSV file
///
/// See the `polars_io::csv::CsvReader`.
///
/// # Indexing
/// ## By a number
///
/// The `Index<usize>` is implemented for the `DataFrame`.
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df = df!("Fruit" => &["Apple", "Apple", "Pear"],
/// "Color" => &["Red", "Yellow", "Green"])?;
///
/// assert_eq!(df[0], Series::new("Fruit", &["Apple", "Apple", "Pear"]));
/// assert_eq!(df[1], Series::new("Color", &["Red", "Yellow", "Green"]));
/// # Ok::<(), PolarsError>(())
/// ```
///
/// ## By a `Series` name
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df = df!("Fruit" => &["Apple", "Apple", "Pear"],
/// "Color" => &["Red", "Yellow", "Green"])?;
///
/// assert_eq!(df["Fruit"], Series::new("Fruit", &["Apple", "Apple", "Pear"]));
/// assert_eq!(df["Color"], Series::new("Color", &["Red", "Yellow", "Green"]));
/// # Ok::<(), PolarsError>(())
/// ```
#[derive(Clone)]
pub struct DataFrame {
pub(crate) columns: Vec<Series>,
}
impl DataFrame {
/// Returns an estimation of the total (heap) allocated size of the `DataFrame` in bytes.
///
/// # Implementation
/// This estimation is the sum of the size of its buffers, validity, including nested arrays.
/// Multiple arrays may share buffers and bitmaps. Therefore, the size of 2 arrays is not the
/// sum of the sizes computed from this function. In particular, [`StructArray`]'s size is an upper bound.
///
/// When an array is sliced, its allocated size remains constant because the buffer unchanged.
/// However, this function will yield a smaller number. This is because this function returns
/// the visible size of the buffer, not its total capacity.
///
/// FFI buffers are included in this estimation.
pub fn estimated_size(&self) -> usize {
self.columns.iter().map(|s| s.estimated_size()).sum()
}
// Reduce monomorphization.
pub fn _apply_columns(&self, func: &(dyn Fn(&Series) -> Series)) -> Vec<Series> {
self.columns.iter().map(func).collect()
}
// Reduce monomorphization.
pub fn _apply_columns_par(
&self,
func: &(dyn Fn(&Series) -> Series + Send + Sync),
) -> Vec<Series> {
POOL.install(|| self.columns.par_iter().map(func).collect())
}
// Reduce monomorphization.
fn try_apply_columns_par(
&self,
func: &(dyn Fn(&Series) -> PolarsResult<Series> + Send + Sync),
) -> PolarsResult<Vec<Series>> {
POOL.install(|| self.columns.par_iter().map(func).collect())
}
// Reduce monomorphization.
fn try_apply_columns(
&self,
func: &(dyn Fn(&Series) -> PolarsResult<Series> + Send + Sync),
) -> PolarsResult<Vec<Series>> {
self.columns.iter().map(func).collect()
}
/// Get the index of the column.
fn check_name_to_idx(&self, name: &str) -> PolarsResult<usize> {
self.get_column_index(name)
.ok_or_else(|| polars_err!(ColumnNotFound: "{}", name))
}
fn check_already_present(&self, name: &str) -> PolarsResult<()> {
polars_ensure!(
self.columns.iter().all(|s| s.name() != name),
Duplicate: "column with name {:?} is already present in the DataFrame", name
);
Ok(())
}
/// Reserve additional slots into the chunks of the series.
pub(crate) fn reserve_chunks(&mut self, additional: usize) {
for s in &mut self.columns {
// Safety
// do not modify the data, simply resize.
unsafe { s.chunks_mut().reserve(additional) }
}
}
/// Create a DataFrame from a Vector of Series.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// let s0 = Series::new("days", [0, 1, 2].as_ref());
/// let s1 = Series::new("temp", [22.1, 19.9, 7.].as_ref());
///
/// let df = DataFrame::new(vec![s0, s1])?;
/// # Ok::<(), PolarsError>(())
/// ```
pub fn new<S: IntoSeries>(columns: Vec<S>) -> PolarsResult<Self> {
let mut first_len = None;
let shape_err = |&first_name, &first_len, &name, &len| {
polars_bail!(
ShapeMismatch: "could not create a new DataFrame: series {:?} has length {} \
while series {:?} has length {}",
first_name, first_len, name, len
);
};
let series_cols = if S::is_series() {
// Safety:
// we are guarded by the type system here.
#[allow(clippy::transmute_undefined_repr)]
let series_cols = unsafe { std::mem::transmute::<Vec<S>, Vec<Series>>(columns) };
let mut names = PlHashSet::with_capacity(series_cols.len());
for s in &series_cols {
let name = s.name();
match first_len {
Some(len) => {
if s.len() != len {
let first_series = &series_cols.first().unwrap();
return shape_err(
&first_series.name(),
&first_series.len(),
&name,
&s.len(),
);
}
},
None => first_len = Some(s.len()),
}
if names.contains(name) {
polars_bail!(duplicate = name);
}
names.insert(name);
}
// we drop early as the brchk thinks the &str borrows are used when calling the drop
// of both `series_cols` and `names`
drop(names);
series_cols
} else {
let mut series_cols: Vec<Series> = Vec::with_capacity(columns.len());
let mut names = PlHashSet::with_capacity(columns.len());
// check for series length equality and convert into series in one pass
for s in columns {
let series = s.into_series();
// we have aliasing borrows so we must allocate a string
let name = series.name().to_string();
match first_len {
Some(len) => {
if series.len() != len {
let first_series = &series_cols.first().unwrap();
return shape_err(
&first_series.name(),
&first_series.len(),
&name.as_str(),
&series.len(),
);
}
},
None => first_len = Some(series.len()),
}
if names.contains(&name) {
polars_bail!(duplicate = name);
}
series_cols.push(series);
names.insert(name);
}
drop(names);
series_cols
};
Ok(DataFrame {
columns: series_cols,
})
}
/// Creates an empty `DataFrame` usable in a compile time context (such as static initializers).
///
/// # Example
///
/// ```rust
/// use polars_core::prelude::DataFrame;
/// static EMPTY: DataFrame = DataFrame::empty();
/// ```
pub const fn empty() -> Self {
DataFrame::new_no_checks(Vec::new())
}
/// Removes the last `Series` from the `DataFrame` and returns it, or [`None`] if it is empty.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let s1 = Series::new("Ocean", &["Atlantic", "Indian"]);
/// let s2 = Series::new("Area (km²)", &[106_460_000, 70_560_000]);
/// let mut df = DataFrame::new(vec![s1.clone(), s2.clone()])?;
///
/// assert_eq!(df.pop(), Some(s2));
/// assert_eq!(df.pop(), Some(s1));
/// assert_eq!(df.pop(), None);
/// assert!(df.is_empty());
/// # Ok::<(), PolarsError>(())
/// ```
pub fn pop(&mut self) -> Option<Series> {
self.columns.pop()
}
/// Add a new column at index 0 that counts the rows.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Name" => &["James", "Mary", "John", "Patricia"])?;
/// assert_eq!(df1.shape(), (4, 1));
///
/// let df2: DataFrame = df1.with_row_index("Id", None)?;
/// assert_eq!(df2.shape(), (4, 2));
/// println!("{}", df2);
///
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (4, 2)
/// +-----+----------+
/// | Id | Name |
/// | --- | --- |
/// | u32 | str |
/// +=====+==========+
/// | 0 | James |
/// +-----+----------+
/// | 1 | Mary |
/// +-----+----------+
/// | 2 | John |
/// +-----+----------+
/// | 3 | Patricia |
/// +-----+----------+
/// ```
pub fn with_row_index(&self, name: &str, offset: Option<IdxSize>) -> PolarsResult<Self> {
let mut columns = Vec::with_capacity(self.columns.len() + 1);
let offset = offset.unwrap_or(0);
let mut ca = IdxCa::from_vec(
name,
(offset..(self.height() as IdxSize) + offset).collect(),
);
ca.set_sorted_flag(IsSorted::Ascending);
columns.push(ca.into_series());
columns.extend_from_slice(&self.columns);
DataFrame::new(columns)
}
/// Add a row index column in place.
pub fn with_row_index_mut(&mut self, name: &str, offset: Option<IdxSize>) -> &mut Self {
let offset = offset.unwrap_or(0);
let mut ca = IdxCa::from_vec(
name,
(offset..(self.height() as IdxSize) + offset).collect(),
);
ca.set_sorted_flag(IsSorted::Ascending);
self.columns.insert(0, ca.into_series());
self
}
/// Create a new `DataFrame` but does not check the length or duplicate occurrence of the `Series`.
///
/// It is advised to use [Series::new](Series::new) in favor of this method.
///
/// # Panic
/// It is the callers responsibility to uphold the contract of all `Series`
/// having an equal length, if not this may panic down the line.
pub const fn new_no_checks(columns: Vec<Series>) -> DataFrame {
DataFrame { columns }
}
/// Create a new `DataFrame` but does not check the length of the `Series`,
/// only check for duplicates.
///
/// It is advised to use [Series::new](Series::new) in favor of this method.
///
/// # Panic
/// It is the callers responsibility to uphold the contract of all `Series`
/// having an equal length, if not this may panic down the line.
pub fn new_no_length_checks(columns: Vec<Series>) -> PolarsResult<DataFrame> {
let mut names = PlHashSet::with_capacity(columns.len());
for column in &columns {
let name = column.name();
if !names.insert(name) {
// If insertion fails, it means the element is already in the set (duplicate)
polars_bail!(duplicate = name)
}
}
// we drop early as the brchk thinks the &str borrows are used when calling the drop
// of both `columns` and `names`
drop(names);
Ok(DataFrame { columns })
}
/// Aggregate all chunks to contiguous memory.
#[must_use]
pub fn agg_chunks(&self) -> Self {
// Don't parallelize this. Memory overhead
let f = |s: &Series| s.rechunk();
let cols = self.columns.iter().map(f).collect();
DataFrame::new_no_checks(cols)
}
/// Shrink the capacity of this DataFrame to fit its length.
pub fn shrink_to_fit(&mut self) {
// Don't parallelize this. Memory overhead
for s in &mut self.columns {
s.shrink_to_fit();
}
}
/// Aggregate all the chunks in the DataFrame to a single chunk.
pub fn as_single_chunk(&mut self) -> &mut Self {
// Don't parallelize this. Memory overhead
for s in &mut self.columns {
*s = s.rechunk();
}
self
}
/// Aggregate all the chunks in the DataFrame to a single chunk in parallel.
/// This may lead to more peak memory consumption.
pub fn as_single_chunk_par(&mut self) -> &mut Self {
if self.columns.iter().any(|s| s.n_chunks() > 1) {
self.columns = self._apply_columns_par(&|s| s.rechunk());
}
self
}
/// Returns true if the chunks of the columns do not align and re-chunking should be done
pub fn should_rechunk(&self) -> bool {
let mut chunk_lengths = self.columns.iter().map(|s| s.chunk_lengths());
match chunk_lengths.next() {
None => false,
Some(first_column_chunk_lengths) => {
// Fast Path for single Chunk Series
if first_column_chunk_lengths.len() == 1 {
return chunk_lengths.any(|cl| cl.len() != 1);
}
// Always rechunk if we have more chunks than rows.
// except when we have an empty df containing a single chunk
let height = self.height();
let n_chunks = first_column_chunk_lengths.len();
if n_chunks > height && !(height == 0 && n_chunks == 1) {
return true;
}
// Slow Path for multi Chunk series
let v: Vec<_> = first_column_chunk_lengths.collect();
for cl in chunk_lengths {
if cl.enumerate().any(|(idx, el)| Some(&el) != v.get(idx)) {
return true;
}
}
false
},
}
}
/// Ensure all the chunks in the [`DataFrame`] are aligned.
pub fn align_chunks(&mut self) -> &mut Self {
if self.should_rechunk() {
self.as_single_chunk_par()
} else {
self
}
}
/// Get the [`DataFrame`] schema.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Thing" => &["Observable universe", "Human stupidity"],
/// "Diameter (m)" => &[8.8e26, f64::INFINITY])?;
///
/// let f1: Field = Field::new("Thing", DataType::String);
/// let f2: Field = Field::new("Diameter (m)", DataType::Float64);
/// let sc: Schema = Schema::from_iter(vec![f1, f2]);
///
/// assert_eq!(df.schema(), sc);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn schema(&self) -> Schema {
self.columns.as_slice().into()
}
/// Get a reference to the [`DataFrame`] columns.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Name" => &["Adenine", "Cytosine", "Guanine", "Thymine"],
/// "Symbol" => &["A", "C", "G", "T"])?;
/// let columns: &[Series] = df.get_columns();
///
/// assert_eq!(columns[0].name(), "Name");
/// assert_eq!(columns[1].name(), "Symbol");
/// # Ok::<(), PolarsError>(())
/// ```
#[inline]
pub fn get_columns(&self) -> &[Series] {
&self.columns
}
#[inline]
/// Get mutable access to the underlying columns.
/// # Safety
/// The caller must ensure the length of all [`Series`] remains equal.
pub unsafe fn get_columns_mut(&mut self) -> &mut Vec<Series> {
&mut self.columns
}
/// Iterator over the columns as [`Series`].
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let s1: Series = Series::new("Name", &["Pythagoras' theorem", "Shannon entropy"]);
/// let s2: Series = Series::new("Formula", &["a²+b²=c²", "H=-Σ[P(x)log|P(x)|]"]);
/// let df: DataFrame = DataFrame::new(vec![s1.clone(), s2.clone()])?;
///
/// let mut iterator = df.iter();
///
/// assert_eq!(iterator.next(), Some(&s1));
/// assert_eq!(iterator.next(), Some(&s2));
/// assert_eq!(iterator.next(), None);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn iter(&self) -> std::slice::Iter<'_, Series> {
self.columns.iter()
}
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Language" => &["Rust", "Python"],
/// "Designer" => &["Graydon Hoare", "Guido van Rossum"])?;
///
/// assert_eq!(df.get_column_names(), &["Language", "Designer"]);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn get_column_names(&self) -> Vec<&str> {
self.columns.iter().map(|s| s.name()).collect()
}
/// Get the [`Vec<String>`] representing the column names.
pub fn get_column_names_owned(&self) -> Vec<SmartString> {
self.columns.iter().map(|s| s.name().into()).collect()
}
/// Set the column names.
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let mut df: DataFrame = df!("Mathematical set" => &["ℕ", "ℤ", "𝔻", "ℚ", "ℝ", "ℂ"])?;
/// df.set_column_names(&["Set"])?;
///
/// assert_eq!(df.get_column_names(), &["Set"]);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn set_column_names<S: AsRef<str>>(&mut self, names: &[S]) -> PolarsResult<()> {
polars_ensure!(
names.len() == self.width(),
ShapeMismatch: "{} column names provided for a DataFrame of width {}",
names.len(), self.width()
);
let unique_names: AHashSet<&str, ahash::RandomState> =
AHashSet::from_iter(names.iter().map(|name| name.as_ref()));
polars_ensure!(
unique_names.len() == self.width(),
Duplicate: "duplicate column names found"
);
let columns = mem::take(&mut self.columns);
self.columns = columns
.into_iter()
.zip(names)
.map(|(s, name)| {
let mut s = s;
s.rename(name.as_ref());
s
})
.collect();
Ok(())
}
/// Get the data types of the columns in the [`DataFrame`].
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let venus_air: DataFrame = df!("Element" => &["Carbon dioxide", "Nitrogen"],
/// "Fraction" => &[0.965, 0.035])?;
///
/// assert_eq!(venus_air.dtypes(), &[DataType::String, DataType::Float64]);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn dtypes(&self) -> Vec<DataType> {
self.columns.iter().map(|s| s.dtype().clone()).collect()
}
/// The number of chunks per column
pub fn n_chunks(&self) -> usize {
match self.columns.first() {
None => 0,
Some(s) => s.n_chunks(),
}
}
/// Get a reference to the schema fields of the [`DataFrame`].
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let earth: DataFrame = df!("Surface type" => &["Water", "Land"],
/// "Fraction" => &[0.708, 0.292])?;
///
/// let f1: Field = Field::new("Surface type", DataType::String);
/// let f2: Field = Field::new("Fraction", DataType::Float64);
///
/// assert_eq!(earth.fields(), &[f1, f2]);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn fields(&self) -> Vec<Field> {
self.columns
.iter()
.map(|s| s.field().into_owned())
.collect()
}
/// Get (height, width) of the [`DataFrame`].
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df0: DataFrame = DataFrame::default();
/// let df1: DataFrame = df!("1" => &[1, 2, 3, 4, 5])?;
/// let df2: DataFrame = df!("1" => &[1, 2, 3, 4, 5],
/// "2" => &[1, 2, 3, 4, 5])?;
///
/// assert_eq!(df0.shape(), (0 ,0));
/// assert_eq!(df1.shape(), (5, 1));
/// assert_eq!(df2.shape(), (5, 2));
/// # Ok::<(), PolarsError>(())
/// ```
pub fn shape(&self) -> (usize, usize) {
match self.columns.as_slice() {
&[] => (0, 0),
v => (v[0].len(), v.len()),
}
}
/// Get the width of the [`DataFrame`] which is the number of columns.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df0: DataFrame = DataFrame::default();
/// let df1: DataFrame = df!("Series 1" => &[0; 0])?;
/// let df2: DataFrame = df!("Series 1" => &[0; 0],
/// "Series 2" => &[0; 0])?;
///
/// assert_eq!(df0.width(), 0);
/// assert_eq!(df1.width(), 1);
/// assert_eq!(df2.width(), 2);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn width(&self) -> usize {
self.columns.len()
}
/// Get the height of the [`DataFrame`] which is the number of rows.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df0: DataFrame = DataFrame::default();
/// let df1: DataFrame = df!("Currency" => &["€", "$"])?;
/// let df2: DataFrame = df!("Currency" => &["€", "$", "¥", "£", "₿"])?;
///
/// assert_eq!(df0.height(), 0);
/// assert_eq!(df1.height(), 2);
/// assert_eq!(df2.height(), 5);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn height(&self) -> usize {
self.shape().0
}
/// Check if the [`DataFrame`] is empty.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df1: DataFrame = DataFrame::default();
/// assert!(df1.is_empty());
///
/// let df2: DataFrame = df!("First name" => &["Forever"],
/// "Last name" => &["Alone"])?;
/// assert!(!df2.is_empty());
/// # Ok::<(), PolarsError>(())
/// ```
pub fn is_empty(&self) -> bool {
self.columns.is_empty()
}
/// Add columns horizontally.
///
/// # Safety
/// The caller must ensure:
/// - the length of all [`Series`] is equal to the height of this [`DataFrame`]
/// - the columns names are unique
pub unsafe fn hstack_mut_unchecked(&mut self, columns: &[Series]) -> &mut Self {
self.columns.extend_from_slice(columns);
self
}
/// Add multiple [`Series`] to a [`DataFrame`].
/// The added `Series` are required to have the same length.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// fn stack(df: &mut DataFrame, columns: &[Series]) {
/// df.hstack_mut(columns);
/// }
/// ```
pub fn hstack_mut(&mut self, columns: &[Series]) -> PolarsResult<&mut Self> {
let mut names = self
.columns
.iter()
.map(|c| c.name())
.collect::<PlHashSet<_>>();
// first loop check validity. We don't do this in a single pass otherwise
// this DataFrame is already modified when an error occurs.
for col in columns {
polars_ensure!(
col.len() == self.height() || self.height() == 0,
ShapeMismatch: "unable to hstack Series of length {} and DataFrame of height {}",
col.len(), self.height(),
);
polars_ensure!(
names.insert(col.name()),
Duplicate: "unable to hstack, column with name {:?} already exists", col.name(),
);
}
drop(names);
Ok(unsafe { self.hstack_mut_unchecked(columns) })
}
/// Add multiple [`Series`] to a [`DataFrame`].
/// The added `Series` are required to have the same length.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Element" => &["Copper", "Silver", "Gold"])?;
/// let s1: Series = Series::new("Proton", &[29, 47, 79]);
/// let s2: Series = Series::new("Electron", &[29, 47, 79]);
///
/// let df2: DataFrame = df1.hstack(&[s1, s2])?;
/// assert_eq!(df2.shape(), (3, 3));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (3, 3)
/// +---------+--------+----------+
/// | Element | Proton | Electron |
/// | --- | --- | --- |
/// | str | i32 | i32 |
/// +=========+========+==========+
/// | Copper | 29 | 29 |
/// +---------+--------+----------+
/// | Silver | 47 | 47 |
/// +---------+--------+----------+
/// | Gold | 79 | 79 |
/// +---------+--------+----------+
/// ```
pub fn hstack(&self, columns: &[Series]) -> PolarsResult<Self> {
let mut new_cols = self.columns.clone();
new_cols.extend_from_slice(columns);
DataFrame::new(new_cols)
}
/// Concatenate a [`DataFrame`] to this [`DataFrame`] and return as newly allocated [`DataFrame`].
///
/// If many `vstack` operations are done, it is recommended to call [`DataFrame::align_chunks`].
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Element" => &["Copper", "Silver", "Gold"],
/// "Melting Point (K)" => &[1357.77, 1234.93, 1337.33])?;
/// let df2: DataFrame = df!("Element" => &["Platinum", "Palladium"],
/// "Melting Point (K)" => &[2041.4, 1828.05])?;
///
/// let df3: DataFrame = df1.vstack(&df2)?;
///
/// assert_eq!(df3.shape(), (5, 2));
/// println!("{}", df3);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (5, 2)
/// +-----------+-------------------+
/// | Element | Melting Point (K) |
/// | --- | --- |
/// | str | f64 |
/// +===========+===================+
/// | Copper | 1357.77 |
/// +-----------+-------------------+
/// | Silver | 1234.93 |
/// +-----------+-------------------+
/// | Gold | 1337.33 |
/// +-----------+-------------------+
/// | Platinum | 2041.4 |
/// +-----------+-------------------+
/// | Palladium | 1828.05 |
/// +-----------+-------------------+
/// ```
pub fn vstack(&self, other: &DataFrame) -> PolarsResult<Self> {
let mut df = self.clone();
df.vstack_mut(other)?;
Ok(df)
}
/// Concatenate a [`DataFrame`] to this [`DataFrame`]
///
/// If many `vstack` operations are done, it is recommended to call [`DataFrame::align_chunks`].
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let mut df1: DataFrame = df!("Element" => &["Copper", "Silver", "Gold"],
/// "Melting Point (K)" => &[1357.77, 1234.93, 1337.33])?;
/// let df2: DataFrame = df!("Element" => &["Platinum", "Palladium"],
/// "Melting Point (K)" => &[2041.4, 1828.05])?;
///
/// df1.vstack_mut(&df2)?;
///
/// assert_eq!(df1.shape(), (5, 2));
/// println!("{}", df1);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (5, 2)
/// +-----------+-------------------+
/// | Element | Melting Point (K) |
/// | --- | --- |
/// | str | f64 |
/// +===========+===================+
/// | Copper | 1357.77 |
/// +-----------+-------------------+
/// | Silver | 1234.93 |
/// +-----------+-------------------+
/// | Gold | 1337.33 |
/// +-----------+-------------------+
/// | Platinum | 2041.4 |
/// +-----------+-------------------+
/// | Palladium | 1828.05 |
/// +-----------+-------------------+
/// ```
pub fn vstack_mut(&mut self, other: &DataFrame) -> PolarsResult<&mut Self> {
if self.width() != other.width() {
polars_ensure!(
self.width() == 0,
ShapeMismatch:
"unable to append to a DataFrame of width {} with a DataFrame of width {}",
self.width(), other.width(),
);
self.columns = other.columns.clone();
return Ok(self);
}
self.columns
.iter_mut()
.zip(other.columns.iter())
.try_for_each::<_, PolarsResult<_>>(|(left, right)| {
ensure_can_extend(left, right)?;
left.append(right)?;
Ok(())
})?;
Ok(self)
}
/// Does not check if schema is correct
pub(crate) fn vstack_mut_unchecked(&mut self, other: &DataFrame) {
self.columns
.iter_mut()
.zip(other.columns.iter())
.for_each(|(left, right)| {
left.append(right).expect("should not fail");
});
}
/// Extend the memory backed by this [`DataFrame`] with the values from `other`.
///
/// Different from [`vstack`](Self::vstack) which adds the chunks from `other` to the chunks of this [`DataFrame`]
/// `extend` appends the data from `other` to the underlying memory locations and thus may cause a reallocation.
///
/// If this does not cause a reallocation, the resulting data structure will not have any extra chunks
/// and thus will yield faster queries.
///
/// Prefer `extend` over `vstack` when you want to do a query after a single append. For instance during
/// online operations where you add `n` rows and rerun a query.
///
/// Prefer `vstack` over `extend` when you want to append many times before doing a query. For instance
/// when you read in multiple files and when to store them in a single `DataFrame`. In the latter case, finish the sequence
/// of `append` operations with a [`rechunk`](Self::align_chunks).
pub fn extend(&mut self, other: &DataFrame) -> PolarsResult<()> {
polars_ensure!(
self.width() == other.width(),
ShapeMismatch:
"unable to extend a DataFrame of width {} with a DataFrame of width {}",
self.width(), other.width(),
);
self.columns
.iter_mut()
.zip(other.columns.iter())
.try_for_each::<_, PolarsResult<_>>(|(left, right)| {
ensure_can_extend(left, right)?;
left.extend(right).unwrap();
Ok(())
})
}
/// Remove a column by name and return the column removed.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let mut df: DataFrame = df!("Animal" => &["Tiger", "Lion", "Great auk"],