Skip to content

Commit

Permalink
pivot index maintain logical type (#3367)
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 committed May 11, 2022
1 parent c075b5a commit 272368b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
19 changes: 13 additions & 6 deletions polars/polars-core/src/frame/groupby/pivot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,15 @@ impl DataFrame {
.collect::<Vec<_>>();

let row_index = match count {
0 => Some(vec![Series::new(
&index[0],
row_to_idx.into_iter().map(|(k, _)| k).collect::<Vec<_>>(),
)]),
0 => {
let s = Series::new(
&index[0],
row_to_idx.into_iter().map(|(k, _)| k).collect::<Vec<_>>(),
);
// restore logical type
let s = s.cast(index_s.dtype()).unwrap();
Some(vec![s])
}
_ => None,
};

Expand Down Expand Up @@ -186,7 +191,7 @@ impl DataFrame {
.iter()
.enumerate()
.map(|(i, name)| {
Series::new(
let s = Series::new(
name,
row_to_idx
.iter()
Expand All @@ -195,7 +200,9 @@ impl DataFrame {
unsafe { k.get_unchecked(i).clone() }
})
.collect::<Vec<_>>(),
)
);
// restore logical type
s.cast(index_s[i].dtype()).unwrap()
})
.collect::<Vec<_>>(),
),
Expand Down
22 changes: 22 additions & 0 deletions polars/tests/it/core/pivot.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use polars::export::chrono::{NaiveDate, NaiveDateTime};
use polars::prelude::*;

#[test]
Expand Down Expand Up @@ -167,3 +168,24 @@ fn test_pivot_2() -> Result<()> {

Ok(())
}

#[test]
#[cfg(feature = "dtype-datetime")]
fn test_pivot_datetime() -> Result<()> {
let dt = NaiveDate::from_ymd(2021, 1, 1).and_hms(12, 15, 0);
let df = df![
"dt" => [dt, dt, dt, dt],
"key" => ["x", "x", "y", "y"],
"val" => [100, 50, 500, -80]
]?;

let out = df.pivot(["val"], ["dt"], ["key"], PivotAgg::Sum, false)?;
let expected = df![
"dt" => [dt],
"x" => [150],
"y" => [420]
]?;
assert!(out.frame_equal(&expected));

Ok(())
}

0 comments on commit 272368b

Please sign in to comment.