Struct polars_core::chunked_array::ChunkedArray
source · pub struct ChunkedArray<T: PolarsDataType> { /* private fields */ }
Expand description
ChunkedArray
Every Series contains a ChunkedArray<T>
. Unlike Series, ChunkedArray’s are typed. This allows
us to apply closures to the data and collect the results to a ChunkedArray
of the same type T
.
Below we use an apply to use the cosine function to the values of a ChunkedArray
.
fn apply_cosine(ca: &Float32Chunked) -> Float32Chunked {
ca.apply(|v| v.cos())
}
If we would like to cast the result we could use a Rust Iterator instead of an apply
method.
Note that Iterators are slightly slower as the null values aren’t ignored implicitly.
fn apply_cosine_and_cast(ca: &Float32Chunked) -> Float64Chunked {
ca.into_iter()
.map(|opt_v| {
opt_v.map(|v| v.cos() as f64)
}).collect()
}
Another option is to first cast and then use an apply.
fn apply_cosine_and_cast(ca: &Float32Chunked) -> Float64Chunked {
ca.apply_cast_numeric(|v| v.cos() as f64)
}
Conversion between Series and ChunkedArray’s
Conversion from a Series
to a ChunkedArray
is effortless.
fn to_chunked_array(series: &Series) -> PolarsResult<&Int32Chunked>{
series.i32()
}
fn to_series(ca: Int32Chunked) -> Series {
ca.into_series()
}
Iterators
ChunkedArrays
fully support Rust native Iterator
and DoubleEndedIterator traits, thereby
giving access to all the excellent methods available for Iterators.
fn iter_forward(ca: &Float32Chunked) {
ca.into_iter()
.for_each(|opt_v| println!("{:?}", opt_v))
}
fn iter_backward(ca: &Float32Chunked) {
ca.into_iter()
.rev()
.for_each(|opt_v| println!("{:?}", opt_v))
}
Memory layout
ChunkedArray
’s use Apache Arrow as backend for the memory layout.
Arrows memory is immutable which makes it possible to make multiple zero copy (sub)-views from a single array.
To be able to append data, Polars uses chunks to append new memory locations, hence the ChunkedArray<T>
data structure.
Appends are cheap, because it will not lead to a full reallocation of the whole array (as could be the case with a Rust Vec).
However, multiple chunks in a ChunkArray
will slow down many operations that need random access because we have an extra indirection
and indexes need to be mapped to the proper chunk. Arithmetic may also be slowed down by this.
When multiplying two ChunkArray'
s with different chunk sizes they cannot utilize SIMD for instance.
If you want to have predictable performance (no unexpected re-allocation of memory), it is advised to call the ChunkedArray::rechunk after multiple append operations.
See also ChunkedArray::extend
for appends within a chunk.
Implementations§
source§impl<T: PolarsNumericType> ChunkedArray<T>where
T::Native: Signed,
impl<T: PolarsNumericType> ChunkedArray<T>where
T::Native: Signed,
sourcepub fn abs(&self) -> Self
pub fn abs(&self) -> Self
Convert all values to their absolute/positive value.
Examples found in repository?
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
pub fn abs(&self) -> PolarsResult<Series> {
let a = self.to_physical_repr();
use DataType::*;
let out = match a.dtype() {
#[cfg(feature = "dtype-i8")]
Int8 => a.i8().unwrap().abs().into_series(),
#[cfg(feature = "dtype-i16")]
Int16 => a.i16().unwrap().abs().into_series(),
Int32 => a.i32().unwrap().abs().into_series(),
Int64 => a.i64().unwrap().abs().into_series(),
UInt8 | UInt16 | UInt32 | UInt64 => self.clone(),
Float32 => a.f32().unwrap().abs().into_series(),
Float64 => a.f64().unwrap().abs().into_series(),
dt => {
return Err(PolarsError::InvalidOperation(
format!("abs not supported for series of type {dt:?}").into(),
));
}
};
Ok(out)
}
source§impl<T> ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkedArray<T>where
T: PolarsNumericType,
sourcepub fn append(&mut self, other: &Self)
pub fn append(&mut self, other: &Self)
Append in place. This is done by adding the chunks of other
to this ChunkedArray
.
See also extend
for appends to the underlying memory
Examples found in repository?
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
pub fn hash_rows(
&mut self,
hasher_builder: Option<RandomState>,
) -> PolarsResult<UInt64Chunked> {
let dfs = split_df(self, POOL.current_num_threads())?;
let (cas, _) = df_rows_to_hashes_threaded(&dfs, hasher_builder)?;
let mut iter = cas.into_iter();
let mut acc_ca = iter.next().unwrap();
for ca in iter {
acc_ca.append(&ca);
}
Ok(acc_ca.rechunk())
}
More examples
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
pub fn extend(&mut self, other: &Self) {
// all to a single chunk
if self.chunks.len() > 1 {
self.append(other);
*self = self.rechunk();
return;
}
// Depending on the state of the underlying arrow array we
// might be able to get a `MutablePrimitiveArray`
//
// This is only possible if the reference count of the array and its buffers are 1
// So the logic below is needed to keep the reference count 1 if it is
// First we must obtain an owned version of the array
let arr = self.downcast_iter().next().unwrap();
// increments 1
let arr = arr.clone();
// now we drop our owned ArrayRefs so that
// decrements 1
{
self.chunks.clear();
}
use Either::*;
match arr.into_mut() {
Left(immutable) => {
extend_immutable(&immutable, &mut self.chunks, &other.chunks);
}
Right(mut mutable) => {
for arr in other.downcast_iter() {
match arr.null_count() {
0 => mutable.extend_from_slice(arr.values()),
_ => mutable.extend_trusted_len(arr.into_iter()),
}
}
let arr: PrimitiveArray<T::Native> = mutable.into();
self.chunks.push(Box::new(arr) as ArrayRef)
}
}
self.compute_len();
self.set_sorted2(IsSorted::Not);
}
source§impl<T: PolarsNumericType> ChunkedArray<T>
impl<T: PolarsNumericType> ChunkedArray<T>
sourcepub fn cast_and_apply_in_place<F, S>(&self, f: F) -> ChunkedArray<S>where
F: Fn(S::Native) -> S::Native + Copy,
S: PolarsNumericType,
pub fn cast_and_apply_in_place<F, S>(&self, f: F) -> ChunkedArray<S>where
F: Fn(S::Native) -> S::Native + Copy,
S: PolarsNumericType,
Cast a numeric array to another numeric data type and apply a function in place. This saves an allocation.
source§impl<T: PolarsNumericType> ChunkedArray<T>
impl<T: PolarsNumericType> ChunkedArray<T>
sourcepub fn apply_mut<F>(&mut self, f: F)where
F: Fn(T::Native) -> T::Native + Copy,
pub fn apply_mut<F>(&mut self, f: F)where
F: Fn(T::Native) -> T::Native + Copy,
Examples found in repository?
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
fn arithmetic_helper_owned<T, Kernel, F>(
mut lhs: ChunkedArray<T>,
mut rhs: ChunkedArray<T>,
kernel: Kernel,
operation: F,
) -> ChunkedArray<T>
where
T: PolarsNumericType,
Kernel: Fn(&mut PrimitiveArray<T::Native>, &mut PrimitiveArray<T::Native>),
F: Fn(T::Native, T::Native) -> T::Native,
{
let ca = match (lhs.len(), rhs.len()) {
(a, b) if a == b => {
let (mut lhs, mut rhs) = align_chunks_binary_owned(lhs, rhs);
// safety, we do no t change the lengths
unsafe {
lhs.downcast_iter_mut()
.zip(rhs.downcast_iter_mut())
.for_each(|(lhs, rhs)| kernel(lhs, rhs));
}
lhs.set_sorted2(IsSorted::Not);
lhs
}
// broadcast right path
(_, 1) => {
let opt_rhs = rhs.get(0);
match opt_rhs {
None => ChunkedArray::full_null(lhs.name(), lhs.len()),
Some(rhs) => {
lhs.apply_mut(|lhs| operation(lhs, rhs));
lhs
}
}
}
(1, _) => {
let opt_lhs = lhs.get(0);
match opt_lhs {
None => ChunkedArray::full_null(lhs.name(), rhs.len()),
Some(lhs_val) => {
rhs.apply_mut(|rhs| operation(lhs_val, rhs));
rhs.rename(lhs.name());
rhs
}
}
}
_ => panic!("Cannot apply operation on arrays of different lengths"),
};
ca
}
// Operands on ChunkedArray & ChunkedArray
impl<T> Add for &ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = ChunkedArray<T>;
fn add(self, rhs: Self) -> Self::Output {
arithmetic_helper(self, rhs, basic::add, |lhs, rhs| lhs + rhs)
}
}
impl<T> Div for &ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = ChunkedArray<T>;
fn div(self, rhs: Self) -> Self::Output {
arithmetic_helper(self, rhs, basic::div, |lhs, rhs| lhs / rhs)
}
}
impl<T> Mul for &ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = ChunkedArray<T>;
fn mul(self, rhs: Self) -> Self::Output {
arithmetic_helper(self, rhs, basic::mul, |lhs, rhs| lhs * rhs)
}
}
impl<T> Rem for &ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = ChunkedArray<T>;
fn rem(self, rhs: Self) -> Self::Output {
arithmetic_helper(self, rhs, basic::rem, |lhs, rhs| lhs % rhs)
}
}
impl<T> Sub for &ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = ChunkedArray<T>;
fn sub(self, rhs: Self) -> Self::Output {
arithmetic_helper(self, rhs, basic::sub, |lhs, rhs| lhs - rhs)
}
}
impl<T> Add for ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
arithmetic_helper_owned(
self,
rhs,
|a, b| arity_assign::binary(a, b, |a, b| a + b),
|lhs, rhs| lhs + rhs,
)
}
}
impl<T> Div for ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
arithmetic_helper_owned(
self,
rhs,
|a, b| arity_assign::binary(a, b, |a, b| a / b),
|lhs, rhs| lhs / rhs,
)
}
}
impl<T> Mul for ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
arithmetic_helper_owned(
self,
rhs,
|a, b| arity_assign::binary(a, b, |a, b| a * b),
|lhs, rhs| lhs * rhs,
)
}
}
impl<T> Sub for ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
arithmetic_helper_owned(
self,
rhs,
|a, b| arity_assign::binary(a, b, |a, b| a - b),
|lhs, rhs| lhs - rhs,
)
}
}
impl<T> Rem for ChunkedArray<T>
where
T: PolarsNumericType,
{
type Output = ChunkedArray<T>;
fn rem(self, rhs: Self) -> Self::Output {
(&self).rem(&rhs)
}
}
// Operands on ChunkedArray & Num
impl<T, N> Add<N> for &ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn add(self, rhs: N) -> Self::Output {
let adder: T::Native = NumCast::from(rhs).unwrap();
self.apply(|val| val + adder)
}
}
impl<T, N> Sub<N> for &ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn sub(self, rhs: N) -> Self::Output {
let subber: T::Native = NumCast::from(rhs).unwrap();
self.apply(|val| val - subber)
}
}
impl<T, N> Div<N> for &ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn div(self, rhs: N) -> Self::Output {
let rhs: T::Native = NumCast::from(rhs).expect("could not cast");
self.apply_kernel(&|arr| Box::new(basic::div_scalar(arr, &rhs)))
}
}
impl<T, N> Mul<N> for &ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn mul(self, rhs: N) -> Self::Output {
let multiplier: T::Native = NumCast::from(rhs).unwrap();
self.apply(|val| val * multiplier)
}
}
impl<T, N> Rem<N> for &ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn rem(self, rhs: N) -> Self::Output {
let rhs: T::Native = NumCast::from(rhs).expect("could not cast");
self.apply_kernel(&|arr| Box::new(basic::rem_scalar(arr, &rhs)))
}
}
impl<T, N> Add<N> for ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn add(mut self, rhs: N) -> Self::Output {
if std::env::var("ASSIGN").is_ok() {
let adder: T::Native = NumCast::from(rhs).unwrap();
self.apply_mut(|val| val + adder);
self
} else {
(&self).add(rhs)
}
}
}
impl<T, N> Sub<N> for ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn sub(mut self, rhs: N) -> Self::Output {
if std::env::var("ASSIGN").is_ok() {
let subber: T::Native = NumCast::from(rhs).unwrap();
self.apply_mut(|val| val - subber);
self
} else {
(&self).sub(rhs)
}
}
}
impl<T, N> Div<N> for ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn div(self, rhs: N) -> Self::Output {
(&self).div(rhs)
}
}
impl<T, N> Mul<N> for ChunkedArray<T>
where
T: PolarsNumericType,
N: Num + ToPrimitive,
{
type Output = ChunkedArray<T>;
fn mul(mut self, rhs: N) -> Self::Output {
if std::env::var("ASSIGN").is_ok() {
let multiplier: T::Native = NumCast::from(rhs).unwrap();
self.apply_mut(|val| val * multiplier);
self
} else {
(&self).mul(rhs)
}
}
source§impl<T: PolarsDataType> ChunkedArray<T>
impl<T: PolarsDataType> ChunkedArray<T>
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Get the length of the ChunkedArray
Examples found in repository?
More examples
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
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Compute the length
pub(crate) fn compute_len(&mut self) {
fn inner(chunks: &[ArrayRef]) -> usize {
match chunks.len() {
// fast path
1 => chunks[0].len(),
_ => chunks.iter().fold(0, |acc, arr| acc + arr.len()),
}
}
self.length = inner(&self.chunks) as IdxSize
}
pub fn rechunk(&self) -> Self {
match self.dtype() {
#[cfg(feature = "object")]
DataType::Object(_) => {
panic!("implementation error")
}
_ => {
fn inner_rechunk(chunks: &[ArrayRef]) -> Vec<ArrayRef> {
vec![concatenate::concatenate(
chunks.iter().map(|a| &**a).collect::<Vec<_>>().as_slice(),
)
.unwrap()]
}
if self.chunks.len() == 1 {
self.clone()
} else {
let chunks = inner_rechunk(&self.chunks);
self.copy_with_chunks(chunks, true)
}
}
}
}
/// Slice the array. The chunks are reallocated the underlying data slices are zero copy.
///
/// When offset is negative it will be counted from the end of the array.
/// This method will never error,
/// and will slice the best match when offset, or length is out of bounds
#[inline]
pub fn slice(&self, offset: i64, length: usize) -> Self {
let (chunks, len) = slice(&self.chunks, offset, length, self.len());
let mut out = self.copy_with_chunks(chunks, true);
out.length = len as IdxSize;
out
}
/// Take a view of top n elements
#[must_use]
pub fn limit(&self, num_elements: usize) -> Self
where
Self: Sized,
{
self.slice(0, num_elements)
}
/// Get the head of the ChunkedArray
#[must_use]
pub fn head(&self, length: Option<usize>) -> Self
where
Self: Sized,
{
match length {
Some(len) => self.slice(0, std::cmp::min(len, self.len())),
None => self.slice(0, std::cmp::min(10, self.len())),
}
}
/// Get the tail of the ChunkedArray
#[must_use]
pub fn tail(&self, length: Option<usize>) -> Self
where
Self: Sized,
{
let len = match length {
Some(len) => std::cmp::min(len, self.len()),
None => std::cmp::min(10, self.len()),
};
self.slice(-(len as i64), len)
}
}
#[cfg(feature = "object")]
impl<T: PolarsObject> ObjectChunked<T> {
pub(crate) fn rechunk_object(&self) -> Self {
if self.chunks.len() == 1 {
self.clone()
} else {
let mut builder = ObjectChunkedBuilder::new(self.name(), self.len());
let chunks = self.downcast_iter();
// todo! use iterators once implemented
// no_null path
if !self.has_validity() {
for arr in chunks {
for idx in 0..arr.len() {
builder.append_value(arr.value(idx).clone())
}
}
} else {
for arr in chunks {
for idx in 0..arr.len() {
if arr.is_valid(idx) {
builder.append_value(arr.value(idx).clone())
} else {
builder.append_null()
}
}
}
}
builder.finish()
}
}
- src/chunked_array/ops/mod.rs
- src/frame/groupby/into_groups.rs
- src/chunked_array/ops/reverse.rs
- src/chunked_array/object/mod.rs
- src/chunked_array/ops/append.rs
- src/frame/hash_join/multiple_keys.rs
- src/series/mod.rs
- src/chunked_array/ops/sort/mod.rs
- src/chunked_array/iterator/mod.rs
- src/chunked_array/ops/take/mod.rs
- src/chunked_array/object/extension/list.rs
- src/chunked_array/ops/repeat_by.rs
- src/functions.rs
- src/chunked_array/ops/sort/argsort_multiple.rs
- src/chunked_array/mod.rs
- src/chunked_array/ops/filter.rs
- src/chunked_array/ops/apply.rs
- src/chunked_array/comparison.rs
- src/vector_hasher.rs
- src/chunked_array/ops/zip.rs
- src/chunked_array/ops/shift.rs
- src/chunked_array/list/iterator.rs
- src/chunked_array/random.rs
- src/fmt.rs
- src/chunked_array/cast.rs
- src/chunked_array/bitwise.rs
- src/chunked_array/arithmetic.rs
- src/chunked_array/ops/set.rs
- src/frame/groupby/aggregations/mod.rs
- src/chunked_array/ops/aggregate.rs
- src/frame/hash_join/single_keys_dispatch.rs
- src/chunked_array/ops/unique/mod.rs
- src/chunked_array/ndarray.rs
- src/utils/mod.rs
- src/frame/groupby/hashing.rs
- src/chunked_array/ops/is_in.rs
- src/frame/asof_join/groups.rs
- src/chunked_array/ops/rolling_window.rs
- src/frame/groupby/mod.rs
- src/frame/groupby/aggregations/agg_list.rs
sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Check if ChunkedArray is empty.
Examples found in repository?
More examples
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
fn append_series(&mut self, s: &Series) {
let arr = s
.as_any()
.downcast_ref::<ObjectChunked<T>>()
.expect("series of type object");
for v in arr.into_iter() {
self.values_builder.append_option(v.cloned())
}
if arr.is_empty() {
self.fast_explode = false;
}
let len_so_far = self.offsets[self.offsets.len() - 1];
self.offsets.push(len_so_far + arr.len() as i64);
}
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
fn apply<F>(&'a self, f: F) -> Self
where
F: Fn(Series) -> Series + Copy,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = true;
let mut function = |s: Series| {
let out = f(s);
if out.is_empty() {
fast_explode = false;
}
out
};
let mut ca: ListChunked = apply!(self, &mut function);
if fast_explode {
ca.set_fast_explode()
}
ca
}
fn try_apply<F>(&'a self, f: F) -> PolarsResult<Self>
where
F: Fn(Series) -> PolarsResult<Series> + Copy,
{
if self.is_empty() {
return Ok(self.clone());
}
let mut fast_explode = true;
let mut function = |s: Series| {
let out = f(s);
if let Ok(out) = &out {
if out.is_empty() {
fast_explode = false;
}
}
out
};
let ca: PolarsResult<ListChunked> = try_apply!(self, &mut function);
let mut ca = ca?;
if fast_explode {
ca.set_fast_explode()
}
Ok(ca)
}
fn apply_on_opt<F>(&'a self, f: F) -> Self
where
F: Fn(Option<Series>) -> Option<Series> + Copy,
{
if self.is_empty() {
return self.clone();
}
self.into_iter().map(f).collect_trusted()
}
/// Apply a closure elementwise. The closure gets the index of the element as first argument.
fn apply_with_idx<F>(&'a self, f: F) -> Self
where
F: Fn((usize, Series)) -> Series + Copy,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = true;
let mut function = |(idx, s)| {
let out = f((idx, s));
if out.is_empty() {
fast_explode = false;
}
out
};
let mut ca: ListChunked = apply_enumerate!(self, function);
if fast_explode {
ca.set_fast_explode()
}
ca
}
/// Apply a closure elementwise. The closure gets the index of the element as first argument.
fn apply_with_idx_on_opt<F>(&'a self, f: F) -> Self
where
F: Fn((usize, Option<Series>)) -> Option<Series> + Copy,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = true;
let function = |(idx, s)| {
let out = f((idx, s));
if let Some(out) = &out {
if out.is_empty() {
fast_explode = false;
}
}
out
};
let mut ca: ListChunked = self.into_iter().enumerate().map(function).collect_trusted();
if fast_explode {
ca.set_fast_explode()
}
ca
}
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
fn sum(&self) -> Option<IdxSize> {
if self.is_empty() {
None
} else {
Some(
self.downcast_iter()
.map(|arr| match arr.validity() {
Some(validity) => {
(arr.len() - (validity & arr.values()).unset_bits()) as IdxSize
}
None => (arr.len() - arr.values().unset_bits()) as IdxSize,
})
.sum(),
)
}
}
fn min(&self) -> Option<IdxSize> {
if self.is_empty() {
return None;
}
if self.all() {
Some(1)
} else {
Some(0)
}
}
fn max(&self) -> Option<IdxSize> {
if self.is_empty() {
return None;
}
if self.any() {
Some(1)
} else {
Some(0)
}
}
fn mean(&self) -> Option<f64> {
self.sum()
.map(|sum| sum as f64 / (self.len() - self.null_count()) as f64)
}
}
// Needs the same trait bounds as the implementation of ChunkedArray<T> of dyn Series
impl<T> ChunkAggSeries for ChunkedArray<T>
where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
ChunkedArray<T>: IntoSeries,
{
fn sum_as_series(&self) -> Series {
let v = self.sum();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = self.max();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = self.min();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn prod_as_series(&self) -> Series {
let mut prod = None;
for opt_v in self.into_iter() {
match (prod, opt_v) {
(_, None) => return Self::full_null(self.name(), 1).into_series(),
(None, Some(v)) => prod = Some(v),
(Some(p), Some(v)) => prod = Some(p * v),
}
}
Self::from_slice_options(self.name(), &[prod]).into_series()
}
}
macro_rules! impl_as_series {
($self:expr, $agg:ident, $ty: ty) => {{
let v = $self.$agg();
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
($self:expr, $agg:ident, $arg:expr, $ty: ty) => {{
let v = $self.$agg($arg);
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
}
impl<T> VarAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
impl VarAggSeries for Float32Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float32Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float32Chunked)
}
}
impl VarAggSeries for Float64Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
macro_rules! impl_quantile_as_series {
($self:expr, $agg:ident, $ty: ty, $qtl:expr, $opt:expr) => {{
let v = $self.$agg($qtl, $opt)?;
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
Ok(ca.into_series())
}};
}
impl<T> QuantileAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl QuantileAggSeries for Float32Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float32Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float32Chunked)
}
}
impl QuantileAggSeries for Float64Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl ChunkAggSeries for BooleanChunked {
fn sum_as_series(&self) -> Series {
let v = ChunkAgg::sum(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = ChunkAgg::max(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = ChunkAgg::min(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
}
impl Utf8Chunked {
pub(crate) fn max_str(&self) -> Option<&str> {
match self.is_sorted2() {
IsSorted::Ascending => self.get(self.len() - 1),
IsSorted::Descending => self.get(0),
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::max_string)
.fold_first_(|acc, v| if acc > v { acc } else { v }),
}
}
pub(crate) fn min_str(&self) -> Option<&str> {
match self.is_sorted2() {
IsSorted::Ascending => self.get(0),
IsSorted::Descending => self.get(self.len() - 1),
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::min_string)
.fold_first_(|acc, v| if acc < v { acc } else { v }),
}
}
}
impl ChunkAggSeries for Utf8Chunked {
fn sum_as_series(&self) -> Series {
Utf8Chunked::full_null(self.name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
Series::new(self.name(), &[self.max_str()])
}
fn min_as_series(&self) -> Series {
Series::new(self.name(), &[self.min_str()])
}
}
#[cfg(feature = "dtype-binary")]
impl ChunkAggSeries for BinaryChunked {
fn sum_as_series(&self) -> Series {
BinaryChunked::full_null(self.name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
Series::new(
self.name(),
&[self
.downcast_iter()
.filter_map(compute::aggregate::max_binary)
.fold_first_(|acc, v| if acc > v { acc } else { v })],
)
}
fn min_as_series(&self) -> Series {
Series::new(
self.name(),
&[self
.downcast_iter()
.filter_map(compute::aggregate::min_binary)
.fold_first_(|acc, v| if acc < v { acc } else { v })],
)
}
}
impl ChunkAggSeries for ListChunked {
fn sum_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
fn max_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
fn min_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
}
#[cfg(feature = "object")]
impl<T: PolarsObject> ChunkAggSeries for ObjectChunked<T> {}
impl<T> ArgAgg for ChunkedArray<T>
where
T: PolarsNumericType,
{
fn arg_min(&self) -> Option<usize> {
match self.is_sorted2() {
IsSorted::Ascending => Some(0),
IsSorted::Descending => Some(self.len()),
IsSorted::Not => self
.into_iter()
.enumerate()
.reduce(|acc, (idx, val)| if acc.1 > val { (idx, val) } else { acc })
.map(|tpl| tpl.0),
}
}
fn arg_max(&self) -> Option<usize> {
match self.is_sorted2() {
IsSorted::Ascending => Some(self.len()),
IsSorted::Descending => Some(0),
IsSorted::Not => self
.into_iter()
.enumerate()
.reduce(|acc, (idx, val)| if acc.1 < val { (idx, val) } else { acc })
.map(|tpl| tpl.0),
}
}
}
impl ArgAgg for BooleanChunked {
fn arg_min(&self) -> Option<usize> {
if self.is_empty() || self.null_count() == self.len() {
None
} else if self.all() {
Some(0)
} else {
self.into_iter()
.position(|opt_val| matches!(opt_val, Some(false)))
}
}
fn arg_max(&self) -> Option<usize> {
if self.is_empty() || self.null_count() == self.len() {
None
} else if self.any() {
self.into_iter()
.position(|opt_val| matches!(opt_val, Some(true)))
} else {
Some(0)
}
}
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
pub fn apply_amortized<'a, F>(&'a self, mut f: F) -> Self
where
F: FnMut(UnstableSeries<'a>) -> Series,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = self.null_count() == 0;
let mut ca: ListChunked = self
.amortized_iter()
.map(|opt_v| {
opt_v.map(|v| {
let out = f(v);
if out.is_empty() {
fast_explode = false;
}
out
})
})
.collect_trusted();
ca.rename(self.name());
if fast_explode {
ca.set_fast_explode();
}
ca
}
pub fn try_apply_amortized<'a, F>(&'a self, mut f: F) -> PolarsResult<Self>
where
F: FnMut(UnstableSeries<'a>) -> PolarsResult<Series>,
{
if self.is_empty() {
return Ok(self.clone());
}
let mut fast_explode = self.null_count() == 0;
let mut ca: ListChunked = self
.amortized_iter()
.map(|opt_v| {
opt_v
.map(|v| {
let out = f(v);
if let Ok(out) = &out {
if out.is_empty() {
fast_explode = false
}
};
out
})
.transpose()
})
.collect::<PolarsResult<_>>()?;
ca.rename(self.name());
if fast_explode {
ca.set_fast_explode();
}
Ok(ca)
}
sourcepub fn rechunk(&self) -> Self
pub fn rechunk(&self) -> Self
Examples found in repository?
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
fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
let indices = if indices.chunks.len() > 1 {
Cow::Owned(indices.rechunk())
} else {
Cow::Borrowed(indices)
};
Ok(ChunkTake::take(&self.0, (&*indices).into())?.into_series())
}
fn take_iter(&self, iter: &mut dyn TakeIterator) -> PolarsResult<Series> {
Ok(ChunkTake::take(&self.0, iter.into())?.into_series())
}
fn take_every(&self, n: usize) -> Series {
self.0.take_every(n).into_series()
}
unsafe fn take_iter_unchecked(&self, iter: &mut dyn TakeIterator) -> Series {
ChunkTake::take_unchecked(&self.0, iter.into()).into_series()
}
unsafe fn take_unchecked(&self, idx: &IdxCa) -> PolarsResult<Series> {
let idx = if idx.chunks.len() > 1 {
Cow::Owned(idx.rechunk())
} else {
Cow::Borrowed(idx)
};
Ok(ChunkTake::take_unchecked(&self.0, (&*idx).into()).into_series())
}
unsafe fn take_opt_iter_unchecked(&self, iter: &mut dyn TakeIteratorNulls) -> Series {
ChunkTake::take_unchecked(&self.0, iter.into()).into_series()
}
#[cfg(feature = "take_opt_iter")]
fn take_opt_iter(&self, iter: &mut dyn TakeIteratorNulls) -> PolarsResult<Series> {
Ok(ChunkTake::take(&self.0, iter.into())?.into_series())
}
fn len(&self) -> usize {
self.0.len()
}
fn rechunk(&self) -> Series {
self.0.rechunk().into_series()
}
More examples
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
fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
let indices = if indices.chunks.len() > 1 {
Cow::Owned(indices.rechunk())
} else {
Cow::Borrowed(indices)
};
Ok(ChunkTake::take(&self.0, (&*indices).into())?.into_series())
}
fn take_iter(&self, iter: &mut dyn TakeIterator) -> PolarsResult<Series> {
Ok(ChunkTake::take(&self.0, iter.into())?.into_series())
}
fn take_every(&self, n: usize) -> Series {
self.0.take_every(n).into_series()
}
unsafe fn take_iter_unchecked(&self, iter: &mut dyn TakeIterator) -> Series {
ChunkTake::take_unchecked(&self.0, iter.into()).into_series()
}
unsafe fn take_unchecked(&self, idx: &IdxCa) -> PolarsResult<Series> {
let idx = if idx.chunks.len() > 1 {
Cow::Owned(idx.rechunk())
} else {
Cow::Borrowed(idx)
};
Ok(ChunkTake::take_unchecked(&self.0, (&*idx).into()).into_series())
}
unsafe fn take_opt_iter_unchecked(&self, iter: &mut dyn TakeIteratorNulls) -> Series {
ChunkTake::take_unchecked(&self.0, iter.into()).into_series()
}
#[cfg(feature = "take_opt_iter")]
fn take_opt_iter(&self, iter: &mut dyn TakeIteratorNulls) -> PolarsResult<Series> {
Ok(ChunkTake::take(&self.0, iter.into())?.into_series())
}
fn len(&self) -> usize {
self.0.len()
}
fn rechunk(&self) -> Series {
self.0.rechunk().into_series()
}
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
fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
let indices = if indices.chunks.len() > 1 {
Cow::Owned(indices.rechunk())
} else {
Cow::Borrowed(indices)
};
Ok(ChunkTake::take(&self.0, (&*indices).into())?.into_series())
}
fn take_iter(&self, iter: &mut dyn TakeIterator) -> PolarsResult<Series> {
Ok(ChunkTake::take(&self.0, iter.into())?.into_series())
}
fn take_every(&self, n: usize) -> Series {
self.0.take_every(n).into_series()
}
unsafe fn take_iter_unchecked(&self, iter: &mut dyn TakeIterator) -> Series {
ChunkTake::take_unchecked(&self.0, iter.into()).into_series()
}
unsafe fn take_unchecked(&self, idx: &IdxCa) -> PolarsResult<Series> {
let idx = if idx.chunks.len() > 1 {
Cow::Owned(idx.rechunk())
} else {
Cow::Borrowed(idx)
};
let mut out = ChunkTake::take_unchecked(&self.0, (&*idx).into());
if self.0.is_sorted() && (idx.is_sorted() || idx.is_sorted_reverse()) {
out.set_sorted2(idx.is_sorted2())
}
Ok(out.into_series())
}
unsafe fn take_opt_iter_unchecked(&self, iter: &mut dyn TakeIteratorNulls) -> Series {
ChunkTake::take_unchecked(&self.0, iter.into()).into_series()
}
#[cfg(feature = "take_opt_iter")]
fn take_opt_iter(&self, iter: &mut dyn TakeIteratorNulls) -> PolarsResult<Series> {
Ok(ChunkTake::take(&self.0, iter.into())?.into_series())
}
fn len(&self) -> usize {
self.0.len()
}
fn rechunk(&self) -> Series {
self.0.rechunk().into_series()
}
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
fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
let indices = if indices.chunks.len() > 1 {
Cow::Owned(indices.rechunk())
} else {
Cow::Borrowed(indices)
};
self.try_with_state(false, |cats| cats.take((&*indices).into()))
.map(|ca| ca.into_series())
}
fn take_iter(&self, iter: &mut dyn TakeIterator) -> PolarsResult<Series> {
let cats = self.0.logical().take(iter.into())?;
Ok(self.finish_with_state(false, cats).into_series())
}
fn take_every(&self, n: usize) -> Series {
self.with_state(true, |cats| cats.take_every(n))
.into_series()
}
unsafe fn take_iter_unchecked(&self, iter: &mut dyn TakeIterator) -> Series {
let cats = self.0.logical().take_unchecked(iter.into());
self.finish_with_state(false, cats).into_series()
}
unsafe fn take_unchecked(&self, idx: &IdxCa) -> PolarsResult<Series> {
let idx = if idx.chunks.len() > 1 {
Cow::Owned(idx.rechunk())
} else {
Cow::Borrowed(idx)
};
Ok(self
.with_state(false, |cats| cats.take_unchecked((&*idx).into()))
.into_series())
}
unsafe fn take_opt_iter_unchecked(&self, iter: &mut dyn TakeIteratorNulls) -> Series {
let cats = self.0.logical().take_unchecked(iter.into());
self.finish_with_state(false, cats).into_series()
}
#[cfg(feature = "take_opt_iter")]
fn take_opt_iter(&self, iter: &mut dyn TakeIteratorNulls) -> PolarsResult<Series> {
let cats = self.0.logical().take(iter.into())?;
Ok(self.finish_with_state(false, cats).into_series())
}
fn len(&self) -> usize {
self.0.len()
}
fn rechunk(&self) -> Series {
self.with_state(true, |ca| ca.rechunk()).into_series()
}
- src/frame/mod.rs
- src/utils/mod.rs
- src/chunked_array/mod.rs
- src/chunked_array/logical/categorical/from.rs
- src/frame/asof_join/mod.rs
- src/chunked_array/ops/extend.rs
- src/chunked_array/cast.rs
- src/frame/groupby/aggregations/mod.rs
- src/chunked_array/ops/take/mod.rs
- src/chunked_array/ops/explode.rs
- src/frame/asof_join/groups.rs
- src/chunked_array/ops/rolling_window.rs
- src/frame/groupby/aggregations/agg_list.rs
- src/chunked_array/ops/unique/rank.rs
sourcepub fn slice(&self, offset: i64, length: usize) -> Self
pub fn slice(&self, offset: i64, length: usize) -> Self
Slice the array. The chunks are reallocated the underlying data slices are zero copy.
When offset is negative it will be counted from the end of the array. This method will never error, and will slice the best match when offset, or length is out of bounds
Examples found in repository?
More examples
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
pub fn limit(&self, num_elements: usize) -> Self
where
Self: Sized,
{
self.slice(0, num_elements)
}
/// Get the head of the ChunkedArray
#[must_use]
pub fn head(&self, length: Option<usize>) -> Self
where
Self: Sized,
{
match length {
Some(len) => self.slice(0, std::cmp::min(len, self.len())),
None => self.slice(0, std::cmp::min(10, self.len())),
}
}
/// Get the tail of the ChunkedArray
#[must_use]
pub fn tail(&self, length: Option<usize>) -> Self
where
Self: Sized,
{
let len = match length {
Some(len) => std::cmp::min(len, self.len()),
None => std::cmp::min(10, self.len()),
};
self.slice(-(len as i64), len)
}
sourcepub fn limit(&self, num_elements: usize) -> Selfwhere
Self: Sized,
pub fn limit(&self, num_elements: usize) -> Selfwhere
Self: Sized,
Take a view of top n elements
source§impl<T> ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkedArray<T>where
T: PolarsNumericType,
sourcepub fn extend(&mut self, other: &Self)
pub fn extend(&mut self, other: &Self)
Extend the memory backed by this array with the values from other
.
Different from ChunkedArray::append
which adds chunks to this ChunkedArray
extend
appends the data from other
to the underlying PrimitiveArray
and thus may cause a reallocation.
However 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 append
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 append
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
.
Examples found in repository?
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
fn extend(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
let other = other.categorical()?;
self.0.logical_mut().extend(other.logical());
let new_rev_map = self.0.merge_categorical_map(other)?;
// safety:
// rev_maps are merged
unsafe { self.0.set_rev_map(new_rev_map, false) };
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot extend Series; data types don't match".into(),
))
}
}
source§impl ChunkedArray<ListType>
impl ChunkedArray<ListType>
sourcepub fn full_null_with_dtype(
name: &str,
length: usize,
inner_dtype: &DataType
) -> ListChunked
pub fn full_null_with_dtype(
name: &str,
length: usize,
inner_dtype: &DataType
) -> ListChunked
Examples found in repository?
More examples
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
pub fn finish(&mut self) -> ListChunked {
let slf = std::mem::take(self);
if slf.builder.is_empty() {
ListChunked::full_null_with_dtype(&slf.name, 0, &slf.dtype.unwrap_or(DataType::Null))
} else {
let dtype = slf.dtype.map(|dt| dt.to_physical().to_arrow());
let arr = slf.builder.finish(dtype.as_ref()).unwrap();
let dtype = DataType::from(arr.data_type());
let mut ca = ListChunked::from_chunks("", vec![Box::new(arr)]);
if self.fast_explode {
ca.set_fast_explode();
}
ca.field = Arc::new(Field::new(&slf.name, dtype));
ca
}
}
}
pub struct AnonymousOwnedListBuilder {
name: String,
builder: AnonymousBuilder<'static>,
owned: Vec<Series>,
inner_dtype: Option<DataType>,
fast_explode: bool,
}
impl Default for AnonymousOwnedListBuilder {
fn default() -> Self {
Self::new("", 0, None)
}
}
impl ListBuilderTrait for AnonymousOwnedListBuilder {
fn append_series(&mut self, s: &Series) {
if s.is_empty() {
self.append_empty();
} else {
// Safety
// we deref a raw pointer with a lifetime that is not static
// it is safe because we also clone Series (Arc +=1) and therefore the &dyn Arrays
// will not be dropped until the owned series are dropped
unsafe {
match s.dtype() {
#[cfg(feature = "dtype-struct")]
DataType::Struct(_) => {
self.builder.push(&*(&**s.array_ref(0) as *const dyn Array))
}
_ => {
self.builder
.push_multiple(&*(s.chunks().as_ref() as *const [ArrayRef]));
}
}
}
// this make sure that the underlying ArrayRef's are not dropped
self.owned.push(s.clone());
}
}
#[inline]
fn append_null(&mut self) {
self.builder.push_null()
}
fn finish(&mut self) -> ListChunked {
let slf = std::mem::take(self);
if slf.builder.is_empty() {
// not really empty, there were empty null list added probably e.g. []
let real_length = slf.builder.offsets().len() - 1;
if real_length > 0 {
let dtype = slf.inner_dtype.unwrap_or(NULL_DTYPE).to_arrow();
let array = new_null_array(dtype.clone(), real_length);
let dtype = ListArray::<i64>::default_datatype(dtype);
let array = ListArray::new(dtype, slf.builder.take_offsets().into(), array, None);
ListChunked::from_chunks(&slf.name, vec![Box::new(array)])
} else {
ListChunked::full_null_with_dtype(
&slf.name,
0,
&slf.inner_dtype.unwrap_or(DataType::Null),
)
}
} else {
let inner_dtype = slf.inner_dtype.map(|dt| dt.to_physical().to_arrow());
let arr = slf.builder.finish(inner_dtype.as_ref()).unwrap();
let dtype = DataType::from(arr.data_type());
let mut ca = ListChunked::from_chunks("", vec![Box::new(arr)]);
if self.fast_explode {
ca.set_fast_explode();
}
ca.field = Arc::new(Field::new(&slf.name, dtype));
ca
}
}
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
fn shift_and_fill(&self, periods: i64, fill_value: Option<&Series>) -> ListChunked {
// This has its own implementation because a ListChunked cannot have a full-null without
// knowing the inner type
let periods = clamp(periods, -(self.len() as i64), self.len() as i64);
let slice_offset = (-periods).max(0);
let length = self.len() - abs(periods) as usize;
let mut slice = self.slice(slice_offset, length);
let fill_length = abs(periods) as usize;
let mut fill = match fill_value {
Some(val) => Self::full(self.name(), val, fill_length),
None => {
ListChunked::full_null_with_dtype(self.name(), fill_length, &self.inner_dtype())
}
};
if periods < 0 {
slice.append(&fill).unwrap();
slice
} else {
fill.append(&slice).unwrap();
fill
}
}
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
fn from_par_iter<I>(iter: I) -> Self
where
I: IntoParallelIterator<Item = Option<Series>>,
{
let mut dtype = None;
let vectors = collect_into_linked_list(iter);
let list_capacity: usize = get_capacity_from_par_results(&vectors);
let value_capacity = vectors
.iter()
.map(|list| {
list.iter()
.map(|opt_s| {
opt_s
.as_ref()
.map(|s| {
if dtype.is_none() && !matches!(s.dtype(), DataType::Null) {
dtype = Some(s.dtype().clone())
}
s.len()
})
.unwrap_or(0)
})
.sum::<usize>()
})
.sum::<usize>();
match &dtype {
#[cfg(feature = "object")]
Some(DataType::Object(_)) => {
let s = vectors
.iter()
.flatten()
.find_map(|opt_s| opt_s.as_ref())
.unwrap();
let mut builder = s.get_list_builder("collected", value_capacity, list_capacity);
for v in vectors {
for val in v {
builder.append_opt_series(val.as_ref());
}
}
builder.finish()
}
Some(dtype) => {
let mut builder =
get_list_builder(dtype, value_capacity, list_capacity, "collected").unwrap();
for v in &vectors {
for val in v {
builder.append_opt_series(val.as_ref());
}
}
builder.finish()
}
None => ListChunked::full_null_with_dtype("collected", list_capacity, &DataType::Null),
}
}
source§impl<T> ChunkedArray<T>where
ChunkedArray<T>: IntoSeries,
T: PolarsFloatType,
T::Native: Float + IsFloat + SubAssign + Pow<T::Native, Output = T::Native>,
impl<T> ChunkedArray<T>where
ChunkedArray<T>: IntoSeries,
T: PolarsFloatType,
T::Native: Float + IsFloat + SubAssign + Pow<T::Native, Output = T::Native>,
sourcepub fn rolling_apply_float<F>(
&self,
window_size: usize,
f: F
) -> PolarsResult<Self>where
F: FnMut(&mut ChunkedArray<T>) -> Option<T::Native>,
pub fn rolling_apply_float<F>(
&self,
window_size: usize,
f: F
) -> PolarsResult<Self>where
F: FnMut(&mut ChunkedArray<T>) -> Option<T::Native>,
Apply a rolling custom function. This is pretty slow because of dynamic dispatch.
source§impl ChunkedArray<BooleanType>
impl ChunkedArray<BooleanType>
sourcepub fn all(&self) -> bool
pub fn all(&self) -> bool
Check if all values are true
Examples found in repository?
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
fn min(&self) -> Option<IdxSize> {
if self.is_empty() {
return None;
}
if self.all() {
Some(1)
} else {
Some(0)
}
}
fn max(&self) -> Option<IdxSize> {
if self.is_empty() {
return None;
}
if self.any() {
Some(1)
} else {
Some(0)
}
}
fn mean(&self) -> Option<f64> {
self.sum()
.map(|sum| sum as f64 / (self.len() - self.null_count()) as f64)
}
}
// Needs the same trait bounds as the implementation of ChunkedArray<T> of dyn Series
impl<T> ChunkAggSeries for ChunkedArray<T>
where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
ChunkedArray<T>: IntoSeries,
{
fn sum_as_series(&self) -> Series {
let v = self.sum();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = self.max();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = self.min();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn prod_as_series(&self) -> Series {
let mut prod = None;
for opt_v in self.into_iter() {
match (prod, opt_v) {
(_, None) => return Self::full_null(self.name(), 1).into_series(),
(None, Some(v)) => prod = Some(v),
(Some(p), Some(v)) => prod = Some(p * v),
}
}
Self::from_slice_options(self.name(), &[prod]).into_series()
}
}
macro_rules! impl_as_series {
($self:expr, $agg:ident, $ty: ty) => {{
let v = $self.$agg();
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
($self:expr, $agg:ident, $arg:expr, $ty: ty) => {{
let v = $self.$agg($arg);
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
}
impl<T> VarAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
impl VarAggSeries for Float32Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float32Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float32Chunked)
}
}
impl VarAggSeries for Float64Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
macro_rules! impl_quantile_as_series {
($self:expr, $agg:ident, $ty: ty, $qtl:expr, $opt:expr) => {{
let v = $self.$agg($qtl, $opt)?;
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
Ok(ca.into_series())
}};
}
impl<T> QuantileAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl QuantileAggSeries for Float32Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float32Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float32Chunked)
}
}
impl QuantileAggSeries for Float64Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl ChunkAggSeries for BooleanChunked {
fn sum_as_series(&self) -> Series {
let v = ChunkAgg::sum(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = ChunkAgg::max(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = ChunkAgg::min(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
}
impl Utf8Chunked {
pub(crate) fn max_str(&self) -> Option<&str> {
match self.is_sorted2() {
IsSorted::Ascending => self.get(self.len() - 1),
IsSorted::Descending => self.get(0),
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::max_string)
.fold_first_(|acc, v| if acc > v { acc } else { v }),
}
}
pub(crate) fn min_str(&self) -> Option<&str> {
match self.is_sorted2() {
IsSorted::Ascending => self.get(0),
IsSorted::Descending => self.get(self.len() - 1),
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::min_string)
.fold_first_(|acc, v| if acc < v { acc } else { v }),
}
}
}
impl ChunkAggSeries for Utf8Chunked {
fn sum_as_series(&self) -> Series {
Utf8Chunked::full_null(self.name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
Series::new(self.name(), &[self.max_str()])
}
fn min_as_series(&self) -> Series {
Series::new(self.name(), &[self.min_str()])
}
}
#[cfg(feature = "dtype-binary")]
impl ChunkAggSeries for BinaryChunked {
fn sum_as_series(&self) -> Series {
BinaryChunked::full_null(self.name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
Series::new(
self.name(),
&[self
.downcast_iter()
.filter_map(compute::aggregate::max_binary)
.fold_first_(|acc, v| if acc > v { acc } else { v })],
)
}
fn min_as_series(&self) -> Series {
Series::new(
self.name(),
&[self
.downcast_iter()
.filter_map(compute::aggregate::min_binary)
.fold_first_(|acc, v| if acc < v { acc } else { v })],
)
}
}
impl ChunkAggSeries for ListChunked {
fn sum_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
fn max_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
fn min_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
}
#[cfg(feature = "object")]
impl<T: PolarsObject> ChunkAggSeries for ObjectChunked<T> {}
impl<T> ArgAgg for ChunkedArray<T>
where
T: PolarsNumericType,
{
fn arg_min(&self) -> Option<usize> {
match self.is_sorted2() {
IsSorted::Ascending => Some(0),
IsSorted::Descending => Some(self.len()),
IsSorted::Not => self
.into_iter()
.enumerate()
.reduce(|acc, (idx, val)| if acc.1 > val { (idx, val) } else { acc })
.map(|tpl| tpl.0),
}
}
fn arg_max(&self) -> Option<usize> {
match self.is_sorted2() {
IsSorted::Ascending => Some(self.len()),
IsSorted::Descending => Some(0),
IsSorted::Not => self
.into_iter()
.enumerate()
.reduce(|acc, (idx, val)| if acc.1 < val { (idx, val) } else { acc })
.map(|tpl| tpl.0),
}
}
}
impl ArgAgg for BooleanChunked {
fn arg_min(&self) -> Option<usize> {
if self.is_empty() || self.null_count() == self.len() {
None
} else if self.all() {
Some(0)
} else {
self.into_iter()
.position(|opt_val| matches!(opt_val, Some(false)))
}
}
More examples
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
fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked> {
match other.dtype() {
DataType::List(dt) if self.dtype() == &**dt => {
let mut ca: BooleanChunked = if self.len() == 1 && other.len() != 1 {
let value = self.get(0);
// safety: we know the iterators len
unsafe {
other
.list()?
.amortized_iter()
.map(|opt_s| {
opt_s.map(|s| {
let ca = s.as_ref().unpack::<BooleanType>().unwrap();
ca.into_iter().any(|a| a == value)
}) == Some(true)
})
.trust_my_length(other.len())
.collect_trusted()
}
} else {
self.into_iter()
.zip(other.list()?.amortized_iter())
.map(|(value, series)| match (value, series) {
(val, Some(series)) => {
let ca = series.as_ref().unpack::<BooleanType>().unwrap();
ca.into_iter().any(|a| a == val)
}
_ => false,
})
.collect_trusted()
};
ca.rename(self.name());
Ok(ca)
}
DataType::Boolean => {
let other = other.bool().unwrap();
let has_true = other.any();
let has_false = !other.all();
Ok(self.apply(|v| if v { has_true } else { has_false }))
}
_ => Err(PolarsError::SchemaMisMatch(
format!(
"cannot do is_in operation with left a dtype: {:?} and right a dtype {:?}",
self.dtype(),
other.dtype()
)
.into(),
)),
}
.map(|mut ca| {
ca.rename(self.name());
ca
})
}
sourcepub fn any(&self) -> bool
pub fn any(&self) -> bool
Check if any value is true
Examples found in repository?
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
fn max(&self) -> Option<IdxSize> {
if self.is_empty() {
return None;
}
if self.any() {
Some(1)
} else {
Some(0)
}
}
fn mean(&self) -> Option<f64> {
self.sum()
.map(|sum| sum as f64 / (self.len() - self.null_count()) as f64)
}
}
// Needs the same trait bounds as the implementation of ChunkedArray<T> of dyn Series
impl<T> ChunkAggSeries for ChunkedArray<T>
where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
ChunkedArray<T>: IntoSeries,
{
fn sum_as_series(&self) -> Series {
let v = self.sum();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = self.max();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = self.min();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn prod_as_series(&self) -> Series {
let mut prod = None;
for opt_v in self.into_iter() {
match (prod, opt_v) {
(_, None) => return Self::full_null(self.name(), 1).into_series(),
(None, Some(v)) => prod = Some(v),
(Some(p), Some(v)) => prod = Some(p * v),
}
}
Self::from_slice_options(self.name(), &[prod]).into_series()
}
}
macro_rules! impl_as_series {
($self:expr, $agg:ident, $ty: ty) => {{
let v = $self.$agg();
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
($self:expr, $agg:ident, $arg:expr, $ty: ty) => {{
let v = $self.$agg($arg);
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
}
impl<T> VarAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
impl VarAggSeries for Float32Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float32Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float32Chunked)
}
}
impl VarAggSeries for Float64Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
macro_rules! impl_quantile_as_series {
($self:expr, $agg:ident, $ty: ty, $qtl:expr, $opt:expr) => {{
let v = $self.$agg($qtl, $opt)?;
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
Ok(ca.into_series())
}};
}
impl<T> QuantileAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl QuantileAggSeries for Float32Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float32Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float32Chunked)
}
}
impl QuantileAggSeries for Float64Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl ChunkAggSeries for BooleanChunked {
fn sum_as_series(&self) -> Series {
let v = ChunkAgg::sum(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = ChunkAgg::max(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = ChunkAgg::min(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
}
impl Utf8Chunked {
pub(crate) fn max_str(&self) -> Option<&str> {
match self.is_sorted2() {
IsSorted::Ascending => self.get(self.len() - 1),
IsSorted::Descending => self.get(0),
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::max_string)
.fold_first_(|acc, v| if acc > v { acc } else { v }),
}
}
pub(crate) fn min_str(&self) -> Option<&str> {
match self.is_sorted2() {
IsSorted::Ascending => self.get(0),
IsSorted::Descending => self.get(self.len() - 1),
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::min_string)
.fold_first_(|acc, v| if acc < v { acc } else { v }),
}
}
}
impl ChunkAggSeries for Utf8Chunked {
fn sum_as_series(&self) -> Series {
Utf8Chunked::full_null(self.name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
Series::new(self.name(), &[self.max_str()])
}
fn min_as_series(&self) -> Series {
Series::new(self.name(), &[self.min_str()])
}
}
#[cfg(feature = "dtype-binary")]
impl ChunkAggSeries for BinaryChunked {
fn sum_as_series(&self) -> Series {
BinaryChunked::full_null(self.name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
Series::new(
self.name(),
&[self
.downcast_iter()
.filter_map(compute::aggregate::max_binary)
.fold_first_(|acc, v| if acc > v { acc } else { v })],
)
}
fn min_as_series(&self) -> Series {
Series::new(
self.name(),
&[self
.downcast_iter()
.filter_map(compute::aggregate::min_binary)
.fold_first_(|acc, v| if acc < v { acc } else { v })],
)
}
}
impl ChunkAggSeries for ListChunked {
fn sum_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
fn max_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
fn min_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
}
#[cfg(feature = "object")]
impl<T: PolarsObject> ChunkAggSeries for ObjectChunked<T> {}
impl<T> ArgAgg for ChunkedArray<T>
where
T: PolarsNumericType,
{
fn arg_min(&self) -> Option<usize> {
match self.is_sorted2() {
IsSorted::Ascending => Some(0),
IsSorted::Descending => Some(self.len()),
IsSorted::Not => self
.into_iter()
.enumerate()
.reduce(|acc, (idx, val)| if acc.1 > val { (idx, val) } else { acc })
.map(|tpl| tpl.0),
}
}
fn arg_max(&self) -> Option<usize> {
match self.is_sorted2() {
IsSorted::Ascending => Some(self.len()),
IsSorted::Descending => Some(0),
IsSorted::Not => self
.into_iter()
.enumerate()
.reduce(|acc, (idx, val)| if acc.1 < val { (idx, val) } else { acc })
.map(|tpl| tpl.0),
}
}
}
impl ArgAgg for BooleanChunked {
fn arg_min(&self) -> Option<usize> {
if self.is_empty() || self.null_count() == self.len() {
None
} else if self.all() {
Some(0)
} else {
self.into_iter()
.position(|opt_val| matches!(opt_val, Some(false)))
}
}
fn arg_max(&self) -> Option<usize> {
if self.is_empty() || self.null_count() == self.len() {
None
} else if self.any() {
self.into_iter()
.position(|opt_val| matches!(opt_val, Some(true)))
} else {
Some(0)
}
}
More examples
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
fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked> {
match other.dtype() {
DataType::List(dt) if self.dtype() == &**dt => {
let mut ca: BooleanChunked = if self.len() == 1 && other.len() != 1 {
let value = self.get(0);
// safety: we know the iterators len
unsafe {
other
.list()?
.amortized_iter()
.map(|opt_s| {
opt_s.map(|s| {
let ca = s.as_ref().unpack::<BooleanType>().unwrap();
ca.into_iter().any(|a| a == value)
}) == Some(true)
})
.trust_my_length(other.len())
.collect_trusted()
}
} else {
self.into_iter()
.zip(other.list()?.amortized_iter())
.map(|(value, series)| match (value, series) {
(val, Some(series)) => {
let ca = series.as_ref().unpack::<BooleanType>().unwrap();
ca.into_iter().any(|a| a == val)
}
_ => false,
})
.collect_trusted()
};
ca.rename(self.name());
Ok(ca)
}
DataType::Boolean => {
let other = other.bool().unwrap();
let has_true = other.any();
let has_false = !other.all();
Ok(self.apply(|v| if v { has_true } else { has_false }))
}
_ => Err(PolarsError::SchemaMisMatch(
format!(
"cannot do is_in operation with left a dtype: {:?} and right a dtype {:?}",
self.dtype(),
other.dtype()
)
.into(),
)),
}
.map(|mut ca| {
ca.rename(self.name());
ca
})
}
source§impl<T> ChunkedArray<T>where
T: PolarsFloatType,
T::Native: Float,
impl<T> ChunkedArray<T>where
T: PolarsFloatType,
T::Native: Float,
sourcepub fn is_nan(&self) -> BooleanChunked
pub fn is_nan(&self) -> BooleanChunked
Examples found in repository?
306 307 308 309 310 311 312 313 314 315 316 317 318
pub fn is_nan(&self) -> PolarsResult<BooleanChunked> {
match self.dtype() {
DataType::Float32 => Ok(self.f32().unwrap().is_nan()),
DataType::Float64 => Ok(self.f64().unwrap().is_nan()),
_ => Err(PolarsError::InvalidOperation(
format!(
"'is_nan' not supported for series with dtype {:?}",
self.dtype()
)
.into(),
)),
}
}
sourcepub fn is_not_nan(&self) -> BooleanChunked
pub fn is_not_nan(&self) -> BooleanChunked
Examples found in repository?
321 322 323 324 325 326 327 328 329 330 331 332 333
pub fn is_not_nan(&self) -> PolarsResult<BooleanChunked> {
match self.dtype() {
DataType::Float32 => Ok(self.f32().unwrap().is_not_nan()),
DataType::Float64 => Ok(self.f64().unwrap().is_not_nan()),
_ => Err(PolarsError::InvalidOperation(
format!(
"'is_not_nan' not supported for series with dtype {:?}",
self.dtype()
)
.into(),
)),
}
}
sourcepub fn is_finite(&self) -> BooleanChunked
pub fn is_finite(&self) -> BooleanChunked
Examples found in repository?
336 337 338 339 340 341 342 343 344 345 346 347 348
pub fn is_finite(&self) -> PolarsResult<BooleanChunked> {
match self.dtype() {
DataType::Float32 => Ok(self.f32().unwrap().is_finite()),
DataType::Float64 => Ok(self.f64().unwrap().is_finite()),
_ => Err(PolarsError::InvalidOperation(
format!(
"'is_finite' not supported for series with dtype {:?}",
self.dtype()
)
.into(),
)),
}
}
sourcepub fn is_infinite(&self) -> BooleanChunked
pub fn is_infinite(&self) -> BooleanChunked
Examples found in repository?
351 352 353 354 355 356 357 358 359 360 361 362 363
pub fn is_infinite(&self) -> PolarsResult<BooleanChunked> {
match self.dtype() {
DataType::Float32 => Ok(self.f32().unwrap().is_infinite()),
DataType::Float64 => Ok(self.f64().unwrap().is_infinite()),
_ => Err(PolarsError::InvalidOperation(
format!(
"'is_infinite' not supported for series with dtype {:?}",
self.dtype()
)
.into(),
)),
}
}
sourcepub fn none_to_nan(&self) -> Self
pub fn none_to_nan(&self) -> Self
Convert missing values to NaN
values.
Examples found in repository?
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
pub fn to_ndarray<N>(&self) -> PolarsResult<Array2<N::Native>>
where
N: PolarsNumericType,
{
let columns = self
.get_columns()
.par_iter()
.map(|s| {
let s = s.cast(&N::get_dtype())?;
let s = match s.dtype() {
DataType::Float32 => {
let ca = s.f32().unwrap();
ca.none_to_nan().into_series()
}
DataType::Float64 => {
let ca = s.f64().unwrap();
ca.none_to_nan().into_series()
}
_ => s,
};
Ok(s.rechunk())
})
.collect::<PolarsResult<Vec<_>>>()?;
let shape = self.shape();
let height = self.height();
let mut membuf = Vec::with_capacity(shape.0 * shape.1);
let ptr = membuf.as_ptr() as usize;
columns.par_iter().enumerate().map(|(col_idx, s)| {
if s.null_count() != 0 {
return Err(PolarsError::ComputeError(
"Creation of ndarray with null values is not supported. Consider using floats and NaNs".into(),
));
}
// this is an Arc clone if already of type N
let s = s.cast(&N::get_dtype())?;
let ca = s.unpack::<N>()?;
let vals = ca.cont_slice().unwrap();
// Safety:
// we get parallel access to the vector
// but we make sure that we don't get aliased access by offsetting the column indices + length
unsafe {
let offset_ptr = (ptr as *mut N::Native).add(col_idx * height) ;
// Safety:
// this is uninitialized memory, so we must never read from this data
// copy_from_slice does not read
let buf = std::slice::from_raw_parts_mut(offset_ptr, height);
buf.copy_from_slice(vals)
}
Ok(())
}).collect::<PolarsResult<Vec<_>>>()?;
// Safety:
// we have written all data, so we can now safely set length
unsafe {
membuf.set_len(shape.0 * shape.1);
}
let ndarr = Array2::from_shape_vec((shape.1, shape.0), membuf).unwrap();
Ok(ndarr.reversed_axes())
}
source§impl ChunkedArray<ListType>
impl ChunkedArray<ListType>
pub fn par_iter(&self) -> impl ParallelIterator<Item = Option<Series>> + '_
pub fn par_iter_indexed(
&mut self
) -> impl IndexedParallelIterator<Item = Option<Series>> + '_
source§impl ChunkedArray<Utf8Type>
impl ChunkedArray<Utf8Type>
pub fn par_iter_indexed(
&self
) -> impl IndexedParallelIterator<Item = Option<&str>>
pub fn par_iter(&self) -> impl ParallelIterator<Item = Option<&str>> + '_
source§impl<T> ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkedArray<T>where
T: PolarsNumericType,
sourcepub fn to_ndarray(&self) -> PolarsResult<ArrayView1<'_, T::Native>>
Available on crate feature ndarray
only.
pub fn to_ndarray(&self) -> PolarsResult<ArrayView1<'_, T::Native>>
ndarray
only.If data is aligned in a single chunk and has no Null values a zero copy view is returned
as an ndarray
Examples found in repository?
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
pub fn to_ndarray<N>(&self) -> PolarsResult<Array2<N::Native>>
where
N: PolarsNumericType,
{
if self.null_count() != 0 {
Err(PolarsError::ComputeError(
"Creation of ndarray with null values is not supported.".into(),
))
} else {
let mut iter = self.into_no_null_iter();
let mut ndarray;
let width;
// first iteration determine the size
if let Some(series) = iter.next() {
width = series.len();
let mut row_idx = 0;
ndarray = ndarray::Array::uninit((self.len(), width));
let series = series.cast(&N::get_dtype())?;
let ca = series.unpack::<N>()?;
let a = ca.to_ndarray()?;
let mut row = ndarray.slice_mut(s![row_idx, ..]);
a.assign_to(&mut row);
row_idx += 1;
for series in iter {
if series.len() != width {
return Err(PolarsError::ShapeMisMatch(
"Could not create a 2D array. Series have different lengths".into(),
));
}
let series = series.cast(&N::get_dtype())?;
let ca = series.unpack::<N>()?;
let a = ca.to_ndarray()?;
let mut row = ndarray.slice_mut(s![row_idx, ..]);
a.assign_to(&mut row);
row_idx += 1;
}
debug_assert_eq!(row_idx, self.len());
// Safety:
// We have assigned to every row and element of the array
unsafe { Ok(ndarray.assume_init()) }
} else {
Err(PolarsError::NoData(
"cannot create ndarray of empty ListChunked".into(),
))
}
}
}
source§impl ChunkedArray<ListType>
impl ChunkedArray<ListType>
sourcepub fn to_ndarray<N>(&self) -> PolarsResult<Array2<N::Native>>where
N: PolarsNumericType,
Available on crate feature ndarray
only.
pub fn to_ndarray<N>(&self) -> PolarsResult<Array2<N::Native>>where
N: PolarsNumericType,
ndarray
only.If all nested Series
have the same length, a 2 dimensional ndarray::Array
is returned.
source§impl<T> ChunkedArray<T>where
T: PolarsDataType,
impl<T> ChunkedArray<T>where
T: PolarsDataType,
sourcepub fn from_chunks(name: &str, chunks: Vec<ArrayRef>) -> Self
pub fn from_chunks(name: &str, chunks: Vec<ArrayRef>) -> Self
Create a new ChunkedArray from existing chunks.
Examples found in repository?
More examples
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
fn full_null(name: &str, length: usize) -> Self {
let arr = new_null_array(T::get_dtype().to_arrow(), length);
ChunkedArray::from_chunks(name, vec![arr])
}
}
impl ChunkFull<bool> for BooleanChunked {
fn full(name: &str, value: bool, length: usize) -> Self {
let mut bits = MutableBitmap::with_capacity(length);
bits.extend_constant(length, value);
let mut out: BooleanChunked =
(name, BooleanArray::from_data_default(bits.into(), None)).into();
out.set_sorted2(IsSorted::Ascending);
out
}
}
impl ChunkFullNull for BooleanChunked {
fn full_null(name: &str, length: usize) -> Self {
let arr = new_null_array(DataType::Boolean.to_arrow(), length);
BooleanChunked::from_chunks(name, vec![arr])
}
}
impl<'a> ChunkFull<&'a str> for Utf8Chunked {
fn full(name: &str, value: &'a str, length: usize) -> Self {
let mut builder = Utf8ChunkedBuilder::new(name, length, length * value.len());
for _ in 0..length {
builder.append_value(value);
}
let mut out = builder.finish();
out.set_sorted2(IsSorted::Ascending);
out
}
}
impl ChunkFullNull for Utf8Chunked {
fn full_null(name: &str, length: usize) -> Self {
let arr = new_null_array(DataType::Utf8.to_arrow(), length);
Utf8Chunked::from_chunks(name, vec![arr])
}
}
#[cfg(feature = "dtype-binary")]
impl<'a> ChunkFull<&'a [u8]> for BinaryChunked {
fn full(name: &str, value: &'a [u8], length: usize) -> Self {
let mut builder = BinaryChunkedBuilder::new(name, length, length * value.len());
for _ in 0..length {
builder.append_value(value);
}
let mut out = builder.finish();
out.set_sorted2(IsSorted::Ascending);
out
}
}
#[cfg(feature = "dtype-binary")]
impl ChunkFullNull for BinaryChunked {
fn full_null(name: &str, length: usize) -> Self {
let arr = new_null_array(DataType::Binary.to_arrow(), length);
BinaryChunked::from_chunks(name, vec![arr])
}
}
impl ChunkFull<&Series> for ListChunked {
fn full(name: &str, value: &Series, length: usize) -> ListChunked {
let mut builder =
get_list_builder(value.dtype(), value.len() * length, length, name).unwrap();
for _ in 0..length {
builder.append_series(value)
}
builder.finish()
}
}
impl ChunkFullNull for ListChunked {
fn full_null(name: &str, length: usize) -> ListChunked {
ListChunked::full_null_with_dtype(name, length, &DataType::Boolean)
}
}
impl ListChunked {
pub fn full_null_with_dtype(name: &str, length: usize, inner_dtype: &DataType) -> ListChunked {
let arr = new_null_array(
ArrowDataType::LargeList(Box::new(ArrowField::new(
"item",
inner_dtype.to_arrow(),
true,
))),
length,
);
ListChunked::from_chunks(name, vec![arr])
}
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
fn from(tpl: (&str, PrimitiveArray<T::Native>)) -> Self {
let name = tpl.0;
let arr = tpl.1;
ChunkedArray::from_chunks(name, vec![Box::new(arr)])
}
}
impl<T: PolarsNumericType> From<&[T::Native]> for ChunkedArray<T> {
fn from(slice: &[T::Native]) -> Self {
ChunkedArray::from_slice("", slice)
}
}
impl From<(&str, BooleanArray)> for BooleanChunked {
fn from(tpl: (&str, BooleanArray)) -> Self {
let name = tpl.0;
let arr = tpl.1;
ChunkedArray::from_chunks(name, vec![Box::new(arr)])
}
}
impl From<BooleanArray> for BooleanChunked {
fn from(arr: BooleanArray) -> Self {
ChunkedArray::from_chunks("", vec![Box::new(arr)])
}
}
impl From<(&str, Utf8Array<i64>)> for Utf8Chunked {
fn from(tpl: (&str, Utf8Array<i64>)) -> Self {
let name = tpl.0;
let arr = tpl.1;
ChunkedArray::from_chunks(name, vec![Box::new(arr)])
}
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
fn from_iter<I: IntoIterator<Item = (Vec<T::Native>, Option<Bitmap>)>>(iter: I) -> Self {
let mut chunks = vec![];
for (values, opt_buffer) in iter {
chunks.push(to_array::<T>(values, opt_buffer))
}
ChunkedArray::from_chunks("from_iter", chunks)
}
}
pub trait NewChunkedArray<T, N> {
fn from_slice(name: &str, v: &[N]) -> Self;
fn from_slice_options(name: &str, opt_v: &[Option<N>]) -> Self;
/// Create a new ChunkedArray from an iterator.
fn from_iter_options(name: &str, it: impl Iterator<Item = Option<N>>) -> Self;
/// Create a new ChunkedArray from an iterator.
fn from_iter_values(name: &str, it: impl Iterator<Item = N>) -> Self;
}
impl<T> NewChunkedArray<T, T::Native> for ChunkedArray<T>
where
T: PolarsNumericType,
{
fn from_slice(name: &str, v: &[T::Native]) -> Self {
let arr = PrimitiveArray::<T::Native>::from_slice(v).to(T::get_dtype().to_arrow());
ChunkedArray::from_chunks(name, vec![Box::new(arr)])
}
fn from_slice_options(name: &str, opt_v: &[Option<T::Native>]) -> Self {
Self::from_iter_options(name, opt_v.iter().copied())
}
fn from_iter_options(
name: &str,
it: impl Iterator<Item = Option<T::Native>>,
) -> ChunkedArray<T> {
let mut builder = PrimitiveChunkedBuilder::new(name, get_iter_capacity(&it));
it.for_each(|opt| builder.append_option(opt));
builder.finish()
}
/// Create a new ChunkedArray from an iterator.
fn from_iter_values(name: &str, it: impl Iterator<Item = T::Native>) -> ChunkedArray<T> {
let ca: NoNull<ChunkedArray<_>> = it.collect();
let mut ca = ca.into_inner();
ca.rename(name);
ca
}
}
impl NewChunkedArray<BooleanType, bool> for BooleanChunked {
fn from_slice(name: &str, v: &[bool]) -> Self {
Self::from_iter_values(name, v.iter().copied())
}
fn from_slice_options(name: &str, opt_v: &[Option<bool>]) -> Self {
Self::from_iter_options(name, opt_v.iter().copied())
}
fn from_iter_options(
name: &str,
it: impl Iterator<Item = Option<bool>>,
) -> ChunkedArray<BooleanType> {
let mut builder = BooleanChunkedBuilder::new(name, get_iter_capacity(&it));
it.for_each(|opt| builder.append_option(opt));
builder.finish()
}
/// Create a new ChunkedArray from an iterator.
fn from_iter_values(name: &str, it: impl Iterator<Item = bool>) -> ChunkedArray<BooleanType> {
let mut ca: ChunkedArray<_> = it.collect();
ca.rename(name);
ca
}
}
impl<S> NewChunkedArray<Utf8Type, S> for Utf8Chunked
where
S: AsRef<str>,
{
fn from_slice(name: &str, v: &[S]) -> Self {
let values_size = v.iter().fold(0, |acc, s| acc + s.as_ref().len());
let mut builder = MutableUtf8Array::<i64>::with_capacities(v.len(), values_size);
builder.extend_trusted_len_values(v.iter().map(|s| s.as_ref()));
let chunks = vec![builder.as_box()];
ChunkedArray::from_chunks(name, chunks)
}
fn from_slice_options(name: &str, opt_v: &[Option<S>]) -> Self {
let values_size = opt_v.iter().fold(0, |acc, s| match s {
Some(s) => acc + s.as_ref().len(),
None => acc,
});
let mut builder = MutableUtf8Array::<i64>::with_capacities(opt_v.len(), values_size);
builder.extend_trusted_len(opt_v.iter().map(|s| s.as_ref()));
let chunks = vec![builder.as_box()];
ChunkedArray::from_chunks(name, chunks)
}
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
fn from_iter_trusted_length<I: IntoIterator<Item = Option<T::Native>>>(iter: I) -> Self {
let iter = iter.into_iter();
let arr = unsafe {
PrimitiveArray::from_trusted_len_iter_unchecked(iter).to(T::get_dtype().to_arrow())
};
ChunkedArray::from_chunks("", vec![Box::new(arr)])
}
}
// NoNull is only a wrapper needed for specialization
impl<T> FromTrustedLenIterator<T::Native> for NoNull<ChunkedArray<T>>
where
T: PolarsNumericType,
{
// We use Vec because it is way faster than Arrows builder. We can do this because we
// know we don't have null values.
fn from_iter_trusted_length<I: IntoIterator<Item = T::Native>>(iter: I) -> Self {
let iter = iter.into_iter();
let values = unsafe { Vec::from_trusted_len_iter_unchecked(iter) }.into();
let arr = PrimitiveArray::new(T::get_dtype().to_arrow(), values, None);
NoNull::new(ChunkedArray::from_chunks("", vec![Box::new(arr)]))
}
}
impl<T> FromIteratorReversed<Option<T::Native>> for ChunkedArray<T>
where
T: PolarsNumericType,
{
fn from_trusted_len_iter_rev<I: TrustedLen<Item = Option<T::Native>>>(iter: I) -> Self {
let size = iter.size_hint().1.unwrap();
let mut vals: Vec<T::Native> = Vec::with_capacity(size);
let mut validity = MutableBitmap::with_capacity(size);
validity.extend_constant(size, true);
let validity_ptr = validity.as_slice().as_ptr() as *mut u8;
unsafe {
// set to end of buffer
let mut ptr = vals.as_mut_ptr().add(size);
let mut offset = size;
iter.for_each(|opt_item| {
offset -= 1;
ptr = ptr.sub(1);
match opt_item {
Some(item) => {
std::ptr::write(ptr, item);
}
None => {
std::ptr::write(ptr, T::Native::default());
unset_bit_raw(validity_ptr, offset)
}
}
});
vals.set_len(size)
}
let arr = PrimitiveArray::new(
T::get_dtype().to_arrow(),
vals.into(),
Some(validity.into()),
);
ChunkedArray::from_chunks("", vec![Box::new(arr)])
}
}
impl FromIteratorReversed<Option<bool>> for BooleanChunked {
fn from_trusted_len_iter_rev<I: TrustedLen<Item = Option<bool>>>(iter: I) -> Self {
let size = iter.size_hint().1.unwrap();
let vals = MutableBitmap::from_len_zeroed(size);
let mut validity = MutableBitmap::with_capacity(size);
validity.extend_constant(size, true);
let validity_ptr = validity.as_slice().as_ptr() as *mut u8;
let vals_ptr = vals.as_slice().as_ptr() as *mut u8;
unsafe {
let mut offset = size;
iter.for_each(|opt_item| {
offset -= 1;
match opt_item {
Some(item) => {
if item {
// set value
// validity bit is already true
set_bit_raw(vals_ptr, offset);
}
}
None => {
// unset validity bit
unset_bit_raw(validity_ptr, offset)
}
}
});
}
let arr = BooleanArray::new(ArrowDataType::Boolean, vals.into(), Some(validity.into()));
ChunkedArray::from_chunks("", vec![Box::new(arr)])
}
}
impl<T> FromIteratorReversed<T::Native> for NoNull<ChunkedArray<T>>
where
T: PolarsNumericType,
{
fn from_trusted_len_iter_rev<I: TrustedLen<Item = T::Native>>(iter: I) -> Self {
let size = iter.size_hint().1.unwrap();
let mut vals: Vec<T::Native> = Vec::with_capacity(size);
unsafe {
// set to end of buffer
let mut ptr = vals.as_mut_ptr().add(size);
iter.for_each(|item| {
ptr = ptr.sub(1);
std::ptr::write(ptr, item);
});
vals.set_len(size)
}
let arr = PrimitiveArray::new(T::get_dtype().to_arrow(), vals.into(), None);
NoNull::new(ChunkedArray::from_chunks("", vec![Box::new(arr)]))
}
}
impl<Ptr> FromTrustedLenIterator<Ptr> for ListChunked
where
Ptr: Borrow<Series>,
{
fn from_iter_trusted_length<I: IntoIterator<Item = Ptr>>(iter: I) -> Self {
let iter = iter.into_iter();
iter.collect()
}
}
impl FromTrustedLenIterator<Option<Series>> for ListChunked {
fn from_iter_trusted_length<I: IntoIterator<Item = Option<Series>>>(iter: I) -> Self {
let iter = iter.into_iter();
iter.collect()
}
}
impl FromTrustedLenIterator<Option<bool>> for ChunkedArray<BooleanType> {
fn from_iter_trusted_length<I: IntoIterator<Item = Option<bool>>>(iter: I) -> Self
where
I::IntoIter: TrustedLen,
{
let iter = iter.into_iter();
let arr: BooleanArray = iter.collect_trusted();
Self::from_chunks("", vec![Box::new(arr)])
}
}
impl FromTrustedLenIterator<bool> for BooleanChunked {
fn from_iter_trusted_length<I: IntoIterator<Item = bool>>(iter: I) -> Self
where
I::IntoIter: TrustedLen,
{
let iter = iter.into_iter();
let arr: BooleanArray = iter.collect_trusted();
Self::from_chunks("", vec![Box::new(arr)])
}
- src/chunked_array/logical/categorical/mod.rs
- src/chunked_array/comparison.rs
- src/series/ops/to_list.rs
- src/chunked_array/ops/repeat_by.rs
- src/chunked_array/mod.rs
- src/chunked_array/ops/concat_str.rs
- src/chunked_array/builder/list.rs
- src/vector_hasher.rs
- src/chunked_array/bitwise.rs
- src/chunked_array/ops/filter.rs
- src/chunked_array/ops/zip.rs
- src/chunked_array/ops/apply.rs
- src/chunked_array/ops/explode.rs
- src/chunked_array/object/extension/list.rs
- src/chunked_array/upstream_traits.rs
- src/chunked_array/ops/set.rs
- src/chunked_array/ops/unique/mod.rs
- src/chunked_array/ops/bit_repr.rs
- src/chunked_array/kernels/take.rs
- src/chunked_array/cast.rs
- src/chunked_array/ops/sort/argsort.rs
- src/series/into.rs
- src/chunked_array/ops/sort/categorical.rs
- src/chunked_array/ops/rolling_window.rs
- src/series/from.rs
- src/frame/groupby/aggregations/mod.rs
- src/frame/row.rs
- src/frame/groupby/aggregations/agg_list.rs
source§impl<T> ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkedArray<T>where
T: PolarsNumericType,
sourcepub fn from_vec(name: &str, v: Vec<T::Native>) -> Self
pub fn from_vec(name: &str, v: Vec<T::Native>) -> Self
Create a new ChunkedArray by taking ownership of the Vec. This operation is zero copy.
Examples found in repository?
More examples
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
fn arg_unique(&self) -> PolarsResult<IdxCa> {
Ok(IdxCa::from_vec(self.name(), arg_unique_ca!(self)))
}
fn is_unique(&self) -> PolarsResult<BooleanChunked> {
is_unique_duplicated!(self, false)
}
fn is_duplicated(&self) -> PolarsResult<BooleanChunked> {
is_unique_duplicated!(self, true)
}
fn n_unique(&self) -> PolarsResult<usize> {
if self.null_count() > 0 {
Ok(fill_set(self.into_iter().flatten()).len() + 1)
} else {
Ok(fill_set(self.into_no_null_iter()).len())
}
}
#[cfg(feature = "mode")]
fn mode(&self) -> PolarsResult<Self> {
Ok(mode(self))
}
}
impl ChunkUnique<Utf8Type> for Utf8Chunked {
fn unique(&self) -> PolarsResult<Self> {
match self.null_count() {
0 => {
let mut set =
PlHashSet::with_capacity(std::cmp::min(HASHMAP_INIT_SIZE, self.len()));
for arr in self.downcast_iter() {
set.extend(arr.values_iter())
}
Ok(Utf8Chunked::from_iter_values(
self.name(),
set.iter().copied(),
))
}
_ => {
let mut set =
PlHashSet::with_capacity(std::cmp::min(HASHMAP_INIT_SIZE, self.len()));
for arr in self.downcast_iter() {
set.extend(arr.iter())
}
Ok(Utf8Chunked::from_iter_options(
self.name(),
set.iter().copied(),
))
}
}
}
fn arg_unique(&self) -> PolarsResult<IdxCa> {
Ok(IdxCa::from_vec(self.name(), arg_unique_ca!(self)))
}
fn is_unique(&self) -> PolarsResult<BooleanChunked> {
is_unique_duplicated!(self, false)
}
fn is_duplicated(&self) -> PolarsResult<BooleanChunked> {
is_unique_duplicated!(self, true)
}
fn n_unique(&self) -> PolarsResult<usize> {
if self.null_count() > 0 {
Ok(fill_set(self.into_iter().flatten()).len() + 1)
} else {
Ok(fill_set(self.into_no_null_iter()).len())
}
}
#[cfg(feature = "mode")]
fn mode(&self) -> PolarsResult<Self> {
Ok(mode(self))
}
}
#[cfg(feature = "dtype-binary")]
impl ChunkUnique<BinaryType> for BinaryChunked {
fn unique(&self) -> PolarsResult<Self> {
match self.null_count() {
0 => {
let mut set =
PlHashSet::with_capacity(std::cmp::min(HASHMAP_INIT_SIZE, self.len()));
for arr in self.downcast_iter() {
set.extend(arr.values_iter())
}
Ok(BinaryChunked::from_iter_values(
self.name(),
set.iter().copied(),
))
}
_ => {
let mut set =
PlHashSet::with_capacity(std::cmp::min(HASHMAP_INIT_SIZE, self.len()));
for arr in self.downcast_iter() {
set.extend(arr.iter())
}
Ok(BinaryChunked::from_iter_options(
self.name(),
set.iter().copied(),
))
}
}
}
fn arg_unique(&self) -> PolarsResult<IdxCa> {
Ok(IdxCa::from_vec(self.name(), arg_unique_ca!(self)))
}
fn is_unique(&self) -> PolarsResult<BooleanChunked> {
is_unique_duplicated!(self, false)
}
fn is_duplicated(&self) -> PolarsResult<BooleanChunked> {
is_unique_duplicated!(self, true)
}
fn n_unique(&self) -> PolarsResult<usize> {
if self.null_count() > 0 {
Ok(fill_set(self.into_iter().flatten()).len() + 1)
} else {
Ok(fill_set(self.into_no_null_iter()).len())
}
}
#[cfg(feature = "mode")]
fn mode(&self) -> PolarsResult<Self> {
Ok(mode(self))
}
}
impl ChunkUnique<BooleanType> for BooleanChunked {
fn unique(&self) -> PolarsResult<Self> {
// can be None, Some(true), Some(false)
let mut unique = Vec::with_capacity(3);
for v in self {
if unique.len() == 3 {
break;
}
if !unique.contains(&v) {
unique.push(v)
}
}
Ok(ChunkedArray::new(self.name(), &unique))
}
fn arg_unique(&self) -> PolarsResult<IdxCa> {
Ok(IdxCa::from_vec(self.name(), arg_unique_ca!(self)))
}
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292
pub fn with_row_count(&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(false);
columns.push(ca.into_series());
columns.extend_from_slice(&self.columns);
DataFrame::new(columns)
}
/// Add a row count in place.
pub fn with_row_count_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(false);
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 }
}
/// 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
}
/// Estimates of the DataFrames columns consist of the same chunk sizes
pub fn should_rechunk(&self) -> bool {
let hb = RandomState::default();
let hb2 = RandomState::with_seeds(392498, 98132457, 0, 412059);
!self
.columns
.iter()
// The idea is that we create a hash of the chunk lengths.
// Consisting of the combined hash + the sum (assuming collision probability is nihil)
// if not, we can add more hashes or at worst case we do an extra rechunk.
// the old solution to this was clone all lengths to a vec and compare the vecs
.map(|s| {
s.chunk_lengths().map(|i| i as u64).fold(
(0u64, 0u64, s.n_chunks()),
|(lhash, lh2, n), rval| {
let mut h = hb.build_hasher();
rval.hash(&mut h);
let rhash = h.finish();
let mut h = hb2.build_hasher();
rval.hash(&mut h);
let rh2 = h.finish();
(
_boost_hash_combine(lhash, rhash),
_boost_hash_combine(lh2, rh2),
n,
)
},
)
})
.all_equal()
}
/// Ensure all the chunks in the DataFrame are aligned.
pub fn rechunk(&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::Utf8);
/// let f2: Field = Field::new("Diameter (m)", DataType::Float64);
/// let sc: Schema = Schema::from(vec![f1, f2].into_iter());
///
/// assert_eq!(df.schema(), sc);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn schema(&self) -> Schema {
Schema::from(self.iter().map(|s| s.field().into_owned()))
}
/// 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: &Vec<Series> = df.get_columns();
///
/// assert_eq!(columns[0].name(), "Name");
/// assert_eq!(columns[1].name(), "Symbol");
/// # Ok::<(), PolarsError>(())
/// ```
#[inline]
pub fn get_columns(&self) -> &Vec<Series> {
&self.columns
}
#[cfg(feature = "private")]
#[inline]
pub 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<String> {
self.columns.iter().map(|s| s.name().to_string()).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<()> {
if names.len() != self.columns.len() {
return Err(PolarsError::ShapeMisMatch("the provided slice with column names has not the same size as the DataFrame's width".into()));
}
let unique_names: AHashSet<&str, ahash::RandomState> =
AHashSet::from_iter(names.iter().map(|name| name.as_ref()));
if unique_names.len() != self.columns.len() {
return Err(PolarsError::SchemaMisMatch(
"duplicate column names found".into(),
));
}
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::Utf8, 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.get(0) {
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::Utf8);
/// 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()
}
pub(crate) fn hstack_mut_no_checks(&mut self, columns: &[Series]) -> &mut Self {
for col in columns {
self.columns.push(col.clone());
}
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 = PlHashSet::with_capacity(self.columns.len());
for s in &self.columns {
names.insert(s.name());
}
let height = self.height();
// 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 {
if col.len() != height && height != 0 {
return Err(PolarsError::ShapeMisMatch(
format!("Could not horizontally stack Series. The Series length {} differs from the DataFrame height: {height}", col.len()).into()));
}
let name = col.name();
if names.contains(name) {
return Err(PolarsError::Duplicate(
format!("Cannot do hstack operation. Column with name: {name} already exists",)
.into(),
));
}
names.insert(name);
}
drop(names);
Ok(self.hstack_mut_no_checks(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::rechunk`].
///
/// # 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::rechunk`].
///
/// # 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() {
if self.width() == 0 {
self.columns = other.columns.clone();
return Ok(self);
}
return Err(PolarsError::ShapeMisMatch(
format!("Could not vertically stack DataFrame. The DataFrames appended width {} differs from the parent DataFrames width {}", self.width(), other.width()).into()
));
}
self.columns
.iter_mut()
.zip(other.columns.iter())
.try_for_each::<_, PolarsResult<_>>(|(left, right)| {
can_extend(left, right)?;
left.append(right).expect("should not fail");
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::rechunk).
pub fn extend(&mut self, other: &DataFrame) -> PolarsResult<()> {
if self.width() != other.width() {
return Err(PolarsError::ShapeMisMatch(
format!("Could not extend DataFrame. The DataFrames extended width {} differs from the parent DataFrames width {}", self.width(), other.width()).into()
));
}
self.columns
.iter_mut()
.zip(other.columns.iter())
.try_for_each::<_, PolarsResult<_>>(|(left, right)| {
can_extend(left, right)?;
left.extend(right).unwrap();
Ok(())
})?;
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"],
/// "IUCN" => &["Endangered", "Vulnerable", "Extinct"])?;
///
/// let s1: PolarsResult<Series> = df.drop_in_place("Average weight");
/// assert!(s1.is_err());
///
/// let s2: Series = df.drop_in_place("Animal")?;
/// assert_eq!(s2, Series::new("Animal", &["Tiger", "Lion", "Great auk"]));
/// # Ok::<(), PolarsError>(())
/// ```
pub fn drop_in_place(&mut self, name: &str) -> PolarsResult<Series> {
let idx = self.check_name_to_idx(name)?;
Ok(self.columns.remove(idx))
}
/// Return a new `DataFrame` where all null values are dropped.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Country" => ["Malta", "Liechtenstein", "North Korea"],
/// "Tax revenue (% GDP)" => [Some(32.7), None, None])?;
/// assert_eq!(df1.shape(), (3, 2));
///
/// let df2: DataFrame = df1.drop_nulls(None)?;
/// assert_eq!(df2.shape(), (1, 2));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (1, 2)
/// +---------+---------------------+
/// | Country | Tax revenue (% GDP) |
/// | --- | --- |
/// | str | f64 |
/// +=========+=====================+
/// | Malta | 32.7 |
/// +---------+---------------------+
/// ```
pub fn drop_nulls(&self, subset: Option<&[String]>) -> PolarsResult<Self> {
let selected_series;
let mut iter = match subset {
Some(cols) => {
selected_series = self.select_series(cols)?;
selected_series.iter()
}
None => self.columns.iter(),
};
// fast path for no nulls in df
if iter.clone().all(|s| !s.has_validity()) {
return Ok(self.clone());
}
let mask = iter
.next()
.ok_or_else(|| PolarsError::NoData("No data to drop nulls from".into()))?;
let mut mask = mask.is_not_null();
for s in iter {
mask = mask & s.is_not_null();
}
self.filter(&mask)
}
/// Drop a column by name.
/// This is a pure method and will return a new `DataFrame` instead of modifying
/// the current one in place.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Ray type" => &["α", "β", "X", "γ"])?;
/// let df2: DataFrame = df1.drop("Ray type")?;
///
/// assert!(df2.is_empty());
/// # Ok::<(), PolarsError>(())
/// ```
pub fn drop(&self, name: &str) -> PolarsResult<Self> {
let idx = self.check_name_to_idx(name)?;
let mut new_cols = Vec::with_capacity(self.columns.len() - 1);
self.columns.iter().enumerate().for_each(|(i, s)| {
if i != idx {
new_cols.push(s.clone())
}
});
Ok(DataFrame::new_no_checks(new_cols))
}
pub fn drop_many<S: AsRef<str>>(&self, names: &[S]) -> Self {
let names = names.iter().map(|s| s.as_ref()).collect();
fn inner(df: &DataFrame, names: Vec<&str>) -> DataFrame {
let mut new_cols = Vec::with_capacity(df.columns.len() - names.len());
df.columns.iter().for_each(|s| {
if !names.contains(&s.name()) {
new_cols.push(s.clone())
}
});
DataFrame::new_no_checks(new_cols)
}
inner(self, names)
}
fn insert_at_idx_no_name_check(
&mut self,
index: usize,
series: Series,
) -> PolarsResult<&mut Self> {
if series.len() == self.height() {
self.columns.insert(index, series);
Ok(self)
} else {
Err(PolarsError::ShapeMisMatch(
format!(
"Could not add column. The Series length {} differs from the DataFrame height: {}",
series.len(),
self.height()
)
.into(),
))
}
}
/// Insert a new column at a given index.
pub fn insert_at_idx<S: IntoSeries>(
&mut self,
index: usize,
column: S,
) -> PolarsResult<&mut Self> {
let series = column.into_series();
self.check_already_present(series.name())?;
self.insert_at_idx_no_name_check(index, series)
}
fn add_column_by_search(&mut self, series: Series) -> PolarsResult<()> {
if let Some(idx) = self.find_idx_by_name(series.name()) {
self.replace_at_idx(idx, series)?;
} else {
self.columns.push(series);
}
Ok(())
}
/// Add a new column to this `DataFrame` or replace an existing one.
pub fn with_column<S: IntoSeries>(&mut self, column: S) -> PolarsResult<&mut Self> {
fn inner(df: &mut DataFrame, mut series: Series) -> PolarsResult<&mut DataFrame> {
let height = df.height();
if series.len() == 1 && height > 1 {
series = series.new_from_index(0, height);
}
if series.len() == height || df.is_empty() {
df.add_column_by_search(series)?;
Ok(df)
}
// special case for literals
else if height == 0 && series.len() == 1 {
let s = series.slice(0, 0);
df.add_column_by_search(s)?;
Ok(df)
} else {
Err(PolarsError::ShapeMisMatch(
format!(
"Could not add column. The Series length {} differs from the DataFrame height: {}",
series.len(),
df.height()
)
.into(),
))
}
}
let series = column.into_series();
inner(self, series)
}
fn add_column_by_schema(&mut self, s: Series, schema: &Schema) -> PolarsResult<()> {
let name = s.name();
if let Some((idx, _, _)) = schema.get_full(name) {
// schema is incorrect fallback to search
if self.columns.get(idx).map(|s| s.name()) != Some(name) {
self.add_column_by_search(s)?;
} else {
self.replace_at_idx(idx, s)?;
}
} else {
self.columns.push(s);
}
Ok(())
}
pub fn _add_columns(&mut self, columns: Vec<Series>, schema: &Schema) -> PolarsResult<()> {
for (i, s) in columns.into_iter().enumerate() {
// we need to branch here
// because users can add multiple columns with the same name
if i == 0 || schema.get(s.name()).is_some() {
self.with_column_and_schema(s, schema)?;
} else {
self.with_column(s.clone())?;
}
}
Ok(())
}
/// Add a new column to this `DataFrame` or replace an existing one.
/// Uses an existing schema to amortize lookups.
/// If the schema is incorrect, we will fallback to linear search.
pub fn with_column_and_schema<S: IntoSeries>(
&mut self,
column: S,
schema: &Schema,
) -> PolarsResult<&mut Self> {
let mut series = column.into_series();
let height = self.height();
if series.len() == 1 && height > 1 {
series = series.new_from_index(0, height);
}
if series.len() == height || self.is_empty() {
self.add_column_by_schema(series, schema)?;
Ok(self)
}
// special case for literals
else if height == 0 && series.len() == 1 {
let s = series.slice(0, 0);
self.add_column_by_schema(s, schema)?;
Ok(self)
} else {
Err(PolarsError::ShapeMisMatch(
format!(
"Could not add column. The Series length {} differs from the DataFrame height: {}",
series.len(),
self.height()
)
.into(),
))
}
}
/// Get a row in the `DataFrame`. Beware this is slow.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// fn example(df: &mut DataFrame, idx: usize) -> Option<Vec<AnyValue>> {
/// df.get(idx)
/// }
/// ```
pub fn get(&self, idx: usize) -> Option<Vec<AnyValue>> {
match self.columns.get(0) {
Some(s) => {
if s.len() <= idx {
return None;
}
}
None => return None,
}
// safety: we just checked bounds
unsafe { Some(self.columns.iter().map(|s| s.get_unchecked(idx)).collect()) }
}
/// Select a `Series` by index.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Star" => &["Sun", "Betelgeuse", "Sirius A", "Sirius B"],
/// "Absolute magnitude" => &[4.83, -5.85, 1.42, 11.18])?;
///
/// let s1: Option<&Series> = df.select_at_idx(0);
/// let s2: Series = Series::new("Star", &["Sun", "Betelgeuse", "Sirius A", "Sirius B"]);
///
/// assert_eq!(s1, Some(&s2));
/// # Ok::<(), PolarsError>(())
/// ```
pub fn select_at_idx(&self, idx: usize) -> Option<&Series> {
self.columns.get(idx)
}
/// Select a mutable series by index.
///
/// *Note: the length of the Series should remain the same otherwise the DataFrame is invalid.*
/// For this reason the method is not public
fn select_at_idx_mut(&mut self, idx: usize) -> Option<&mut Series> {
self.columns.get_mut(idx)
}
/// Select column(s) from this `DataFrame` by range and return a new DataFrame
///
/// # Examples
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df = df! {
/// "0" => &[0, 0, 0],
/// "1" => &[1, 1, 1],
/// "2" => &[2, 2, 2]
/// }?;
///
/// assert!(df.select(&["0", "1"])?.frame_equal(&df.select_by_range(0..=1)?));
/// assert!(df.frame_equal(&df.select_by_range(..)?));
/// # Ok::<(), PolarsError>(())
/// ```
pub fn select_by_range<R>(&self, range: R) -> PolarsResult<Self>
where
R: ops::RangeBounds<usize>,
{
// This function is copied from std::slice::range (https://doc.rust-lang.org/std/slice/fn.range.html)
// because it is the nightly feature. We should change here if this function were stable.
fn get_range<R>(range: R, bounds: ops::RangeTo<usize>) -> ops::Range<usize>
where
R: ops::RangeBounds<usize>,
{
let len = bounds.end;
let start: ops::Bound<&usize> = range.start_bound();
let start = match start {
ops::Bound::Included(&start) => start,
ops::Bound::Excluded(start) => start.checked_add(1).unwrap_or_else(|| {
panic!("attempted to index slice from after maximum usize");
}),
ops::Bound::Unbounded => 0,
};
let end: ops::Bound<&usize> = range.end_bound();
let end = match end {
ops::Bound::Included(end) => end.checked_add(1).unwrap_or_else(|| {
panic!("attempted to index slice up to maximum usize");
}),
ops::Bound::Excluded(&end) => end,
ops::Bound::Unbounded => len,
};
if start > end {
panic!("slice index starts at {start} but ends at {end}");
}
if end > len {
panic!("range end index {end} out of range for slice of length {len}",);
}
ops::Range { start, end }
}
let colnames = self.get_column_names_owned();
let range = get_range(range, ..colnames.len());
self.select_impl(&colnames[range])
}
/// Get column index of a `Series` by name.
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Name" => &["Player 1", "Player 2", "Player 3"],
/// "Health" => &[100, 200, 500],
/// "Mana" => &[250, 100, 0],
/// "Strength" => &[30, 150, 300])?;
///
/// assert_eq!(df.find_idx_by_name("Name"), Some(0));
/// assert_eq!(df.find_idx_by_name("Health"), Some(1));
/// assert_eq!(df.find_idx_by_name("Mana"), Some(2));
/// assert_eq!(df.find_idx_by_name("Strength"), Some(3));
/// assert_eq!(df.find_idx_by_name("Haste"), None);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn find_idx_by_name(&self, name: &str) -> Option<usize> {
self.columns.iter().position(|s| s.name() == name)
}
/// Select a single column by name.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let s1: Series = Series::new("Password", &["123456", "[]B$u$g$s$B#u#n#n#y[]{}"]);
/// let s2: Series = Series::new("Robustness", &["Weak", "Strong"]);
/// let df: DataFrame = DataFrame::new(vec![s1.clone(), s2])?;
///
/// assert_eq!(df.column("Password")?, &s1);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn column(&self, name: &str) -> PolarsResult<&Series> {
let idx = self
.find_idx_by_name(name)
.ok_or_else(|| PolarsError::NotFound(name.to_string().into()))?;
Ok(self.select_at_idx(idx).unwrap())
}
/// Selected multiple columns by name.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Latin name" => &["Oncorhynchus kisutch", "Salmo salar"],
/// "Max weight (kg)" => &[16.0, 35.89])?;
/// let sv: Vec<&Series> = df.columns(&["Latin name", "Max weight (kg)"])?;
///
/// assert_eq!(&df[0], sv[0]);
/// assert_eq!(&df[1], sv[1]);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn columns<I, S>(&self, names: I) -> PolarsResult<Vec<&Series>>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
names
.into_iter()
.map(|name| self.column(name.as_ref()))
.collect()
}
/// Select column(s) from this `DataFrame` and return a new `DataFrame`.
///
/// # Examples
///
/// ```
/// # use polars_core::prelude::*;
/// fn example(df: &DataFrame) -> PolarsResult<DataFrame> {
/// df.select(["foo", "bar"])
/// }
/// ```
pub fn select<I, S>(&self, selection: I) -> PolarsResult<Self>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let cols = selection
.into_iter()
.map(|s| s.as_ref().to_string())
.collect::<Vec<_>>();
self.select_impl(&cols)
}
fn select_impl(&self, cols: &[String]) -> PolarsResult<Self> {
self.select_check_duplicates(cols)?;
let selected = self.select_series_impl(cols)?;
Ok(DataFrame::new_no_checks(selected))
}
pub fn select_physical<I, S>(&self, selection: I) -> PolarsResult<Self>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let cols = selection
.into_iter()
.map(|s| s.as_ref().to_string())
.collect::<Vec<_>>();
self.select_physical_impl(&cols)
}
fn select_physical_impl(&self, cols: &[String]) -> PolarsResult<Self> {
self.select_check_duplicates(cols)?;
let selected = self.select_series_physical_impl(cols)?;
Ok(DataFrame::new_no_checks(selected))
}
fn select_check_duplicates(&self, cols: &[String]) -> PolarsResult<()> {
let mut names = PlHashSet::with_capacity(cols.len());
for name in cols {
if !names.insert(name.as_str()) {
_duplicate_err(name)?
}
}
Ok(())
}
/// Select column(s) from this `DataFrame` and return them into a `Vec`.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Name" => &["Methane", "Ethane", "Propane"],
/// "Carbon" => &[1, 2, 3],
/// "Hydrogen" => &[4, 6, 8])?;
/// let sv: Vec<Series> = df.select_series(&["Carbon", "Hydrogen"])?;
///
/// assert_eq!(df["Carbon"], sv[0]);
/// assert_eq!(df["Hydrogen"], sv[1]);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn select_series(&self, selection: impl IntoVec<String>) -> PolarsResult<Vec<Series>> {
let cols = selection.into_vec();
self.select_series_impl(&cols)
}
fn _names_to_idx_map(&self) -> PlHashMap<&str, usize> {
self.columns
.iter()
.enumerate()
.map(|(i, s)| (s.name(), i))
.collect()
}
/// A non generic implementation to reduce compiler bloat.
fn select_series_physical_impl(&self, cols: &[String]) -> PolarsResult<Vec<Series>> {
let selected = if cols.len() > 1 && self.columns.len() > 10 {
let name_to_idx = self._names_to_idx_map();
cols.iter()
.map(|name| {
let idx = *name_to_idx
.get(name.as_str())
.ok_or_else(|| PolarsError::NotFound(name.to_string().into()))?;
Ok(self
.select_at_idx(idx)
.unwrap()
.to_physical_repr()
.into_owned())
})
.collect::<PolarsResult<Vec<_>>>()?
} else {
cols.iter()
.map(|c| self.column(c).map(|s| s.to_physical_repr().into_owned()))
.collect::<PolarsResult<Vec<_>>>()?
};
Ok(selected)
}
/// A non generic implementation to reduce compiler bloat.
fn select_series_impl(&self, cols: &[String]) -> PolarsResult<Vec<Series>> {
let selected = if cols.len() > 1 && self.columns.len() > 10 {
// we hash, because there are user that having millions of columns.
// # https://github.com/pola-rs/polars/issues/1023
let name_to_idx = self._names_to_idx_map();
cols.iter()
.map(|name| {
let idx = *name_to_idx
.get(name.as_str())
.ok_or_else(|| PolarsError::NotFound(name.to_string().into()))?;
Ok(self.select_at_idx(idx).unwrap().clone())
})
.collect::<PolarsResult<Vec<_>>>()?
} else {
cols.iter()
.map(|c| self.column(c).map(|s| s.clone()))
.collect::<PolarsResult<Vec<_>>>()?
};
Ok(selected)
}
/// Select a mutable series by name.
/// *Note: the length of the Series should remain the same otherwise the DataFrame is invalid.*
/// For this reason the method is not public
fn select_mut(&mut self, name: &str) -> Option<&mut Series> {
let opt_idx = self.find_idx_by_name(name);
match opt_idx {
Some(idx) => self.select_at_idx_mut(idx),
None => None,
}
}
/// Does a filter but splits thread chunks vertically instead of horizontally
/// This yields a DataFrame with `n_chunks == n_threads`.
fn filter_vertical(&mut self, mask: &BooleanChunked) -> PolarsResult<Self> {
let n_threads = POOL.current_num_threads();
let masks = split_ca(mask, n_threads).unwrap();
let dfs = split_df(self, n_threads).unwrap();
let dfs: PolarsResult<Vec<_>> = POOL.install(|| {
masks
.par_iter()
.zip(dfs)
.map(|(mask, df)| {
let cols = df
.columns
.iter()
.map(|s| s.filter(mask))
.collect::<PolarsResult<_>>()?;
Ok(DataFrame::new_no_checks(cols))
})
.collect()
});
let mut iter = dfs?.into_iter();
let first = iter.next().unwrap();
Ok(iter.fold(first, |mut acc, df| {
acc.vstack_mut(&df).unwrap();
acc
}))
}
/// Take the `DataFrame` rows by a boolean mask.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// fn example(df: &DataFrame) -> PolarsResult<DataFrame> {
/// let mask = df.column("sepal.width")?.is_not_null();
/// df.filter(&mask)
/// }
/// ```
pub fn filter(&self, mask: &BooleanChunked) -> PolarsResult<Self> {
if std::env::var("POLARS_VERT_PAR").is_ok() {
return self.clone().filter_vertical(mask);
}
let new_col = self.try_apply_columns_par(&|s| match s.dtype() {
DataType::Utf8 => s.filter_threaded(mask, true),
_ => s.filter(mask),
})?;
Ok(DataFrame::new_no_checks(new_col))
}
/// Same as `filter` but does not parallelize.
pub fn _filter_seq(&self, mask: &BooleanChunked) -> PolarsResult<Self> {
let new_col = self.try_apply_columns(&|s| s.filter(mask))?;
Ok(DataFrame::new_no_checks(new_col))
}
/// Take `DataFrame` value by indexes from an iterator.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// fn example(df: &DataFrame) -> PolarsResult<DataFrame> {
/// let iterator = (0..9).into_iter();
/// df.take_iter(iterator)
/// }
/// ```
pub fn take_iter<I>(&self, iter: I) -> PolarsResult<Self>
where
I: Iterator<Item = usize> + Clone + Sync + TrustedLen,
{
let new_col = self.try_apply_columns_par(&|s| {
let mut i = iter.clone();
s.take_iter(&mut i)
})?;
Ok(DataFrame::new_no_checks(new_col))
}
/// Take `DataFrame` values by indexes from an iterator.
///
/// # Safety
///
/// This doesn't do any bound checking but checks null validity.
#[must_use]
pub unsafe fn take_iter_unchecked<I>(&self, mut iter: I) -> Self
where
I: Iterator<Item = usize> + Clone + Sync + TrustedLen,
{
if std::env::var("POLARS_VERT_PAR").is_ok() {
let idx_ca: NoNull<IdxCa> = iter.into_iter().map(|idx| idx as IdxSize).collect();
return self.take_unchecked_vectical(&idx_ca.into_inner());
}
let n_chunks = self.n_chunks();
let has_utf8 = self
.columns
.iter()
.any(|s| matches!(s.dtype(), DataType::Utf8));
if (n_chunks == 1 && self.width() > 1) || has_utf8 {
let idx_ca: NoNull<IdxCa> = iter.into_iter().map(|idx| idx as IdxSize).collect();
let idx_ca = idx_ca.into_inner();
return self.take_unchecked(&idx_ca);
}
let new_col = if self.width() == 1 {
self.columns
.iter()
.map(|s| s.take_iter_unchecked(&mut iter))
.collect::<Vec<_>>()
} else {
self.apply_columns_par(&|s| {
let mut i = iter.clone();
s.take_iter_unchecked(&mut i)
})
};
DataFrame::new_no_checks(new_col)
}
/// Take `DataFrame` values by indexes from an iterator that may contain None values.
///
/// # Safety
///
/// This doesn't do any bound checking. Out of bounds may access uninitialized memory.
/// Null validity is checked
#[must_use]
pub unsafe fn take_opt_iter_unchecked<I>(&self, mut iter: I) -> Self
where
I: Iterator<Item = Option<usize>> + Clone + Sync + TrustedLen,
{
if std::env::var("POLARS_VERT_PAR").is_ok() {
let idx_ca: IdxCa = iter
.into_iter()
.map(|opt| opt.map(|v| v as IdxSize))
.collect();
return self.take_unchecked_vectical(&idx_ca);
}
let n_chunks = self.n_chunks();
let has_utf8 = self
.columns
.iter()
.any(|s| matches!(s.dtype(), DataType::Utf8));
if (n_chunks == 1 && self.width() > 1) || has_utf8 {
let idx_ca: IdxCa = iter
.into_iter()
.map(|opt| opt.map(|v| v as IdxSize))
.collect();
return self.take_unchecked(&idx_ca);
}
let new_col = if self.width() == 1 {
self.columns
.iter()
.map(|s| s.take_opt_iter_unchecked(&mut iter))
.collect::<Vec<_>>()
} else {
self.apply_columns_par(&|s| {
let mut i = iter.clone();
s.take_opt_iter_unchecked(&mut i)
})
};
DataFrame::new_no_checks(new_col)
}
/// Take `DataFrame` rows by index values.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// fn example(df: &DataFrame) -> PolarsResult<DataFrame> {
/// let idx = IdxCa::new("idx", &[0, 1, 9]);
/// df.take(&idx)
/// }
/// ```
pub fn take(&self, indices: &IdxCa) -> PolarsResult<Self> {
let indices = if indices.chunks.len() > 1 {
Cow::Owned(indices.rechunk())
} else {
Cow::Borrowed(indices)
};
let new_col = POOL.install(|| {
self.try_apply_columns_par(&|s| match s.dtype() {
DataType::Utf8 => s.take_threaded(&indices, true),
_ => s.take(&indices),
})
})?;
Ok(DataFrame::new_no_checks(new_col))
}
pub(crate) unsafe fn take_unchecked(&self, idx: &IdxCa) -> Self {
self.take_unchecked_impl(idx, true)
}
unsafe fn take_unchecked_impl(&self, idx: &IdxCa, allow_threads: bool) -> Self {
let cols = if allow_threads {
POOL.install(|| {
self.apply_columns_par(&|s| match s.dtype() {
DataType::Utf8 => s.take_unchecked_threaded(idx, true).unwrap(),
_ => s.take_unchecked(idx).unwrap(),
})
})
} else {
self.columns
.iter()
.map(|s| s.take_unchecked(idx).unwrap())
.collect()
};
DataFrame::new_no_checks(cols)
}
unsafe fn take_unchecked_vectical(&self, indices: &IdxCa) -> Self {
let n_threads = POOL.current_num_threads();
let idxs = split_ca(indices, n_threads).unwrap();
let dfs: Vec<_> = POOL.install(|| {
idxs.par_iter()
.map(|idx| {
let cols = self
.columns
.iter()
.map(|s| s.take_unchecked(idx).unwrap())
.collect();
DataFrame::new_no_checks(cols)
})
.collect()
});
let mut iter = dfs.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |mut acc, df| {
acc.vstack_mut(&df).unwrap();
acc
})
}
/// Rename a column in the `DataFrame`.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// fn example(df: &mut DataFrame) -> PolarsResult<&mut DataFrame> {
/// let original_name = "foo";
/// let new_name = "bar";
/// df.rename(original_name, new_name)
/// }
/// ```
pub fn rename(&mut self, column: &str, name: &str) -> PolarsResult<&mut Self> {
self.select_mut(column)
.ok_or_else(|| PolarsError::NotFound(column.to_string().into()))
.map(|s| s.rename(name))?;
let unique_names: AHashSet<&str, ahash::RandomState> =
AHashSet::from_iter(self.columns.iter().map(|s| s.name()));
if unique_names.len() != self.columns.len() {
return Err(PolarsError::SchemaMisMatch(
"duplicate column names found".into(),
));
}
Ok(self)
}
/// Sort `DataFrame` in place by a column.
pub fn sort_in_place(
&mut self,
by_column: impl IntoVec<String>,
reverse: impl IntoVec<bool>,
) -> PolarsResult<&mut Self> {
// a lot of indirection in both sorting and take
self.as_single_chunk_par();
let by_column = self.select_series(by_column)?;
let reverse = reverse.into_vec();
self.columns = self.sort_impl(by_column, reverse, false, None)?.columns;
Ok(self)
}
/// This is the dispatch of Self::sort, and exists to reduce compile bloat by monomorphization.
#[cfg(feature = "private")]
pub fn sort_impl(
&self,
by_column: Vec<Series>,
reverse: Vec<bool>,
nulls_last: bool,
slice: Option<(i64, usize)>,
) -> PolarsResult<Self> {
// note that the by_column argument also contains evaluated expression from polars-lazy
// that may not even be present in this dataframe.
// therefore when we try to set the first columns as sorted, we ignore the error
// as expressions are not present (they are renamed to _POLARS_SORT_COLUMN_i.
let first_reverse = reverse[0];
let first_by_column = by_column[0].name().to_string();
let mut take = match by_column.len() {
1 => {
let s = &by_column[0];
let options = SortOptions {
descending: reverse[0],
nulls_last,
};
// fast path for a frame with a single series
// no need to compute the sort indices and then take by these indices
// simply sort and return as frame
if self.width() == 1 && self.check_name_to_idx(s.name()).is_ok() {
let mut out = s.sort_with(options);
if let Some((offset, len)) = slice {
out = out.slice(offset, len);
}
return Ok(out.into_frame());
}
s.argsort(options)
}
_ => {
#[cfg(feature = "sort_multiple")]
{
let (first, by_column, reverse) = prepare_argsort(by_column, reverse)?;
first.argsort_multiple(&by_column, &reverse)?
}
#[cfg(not(feature = "sort_multiple"))]
{
panic!("activate `sort_multiple` feature gate to enable this functionality");
}
}
};
if let Some((offset, len)) = slice {
take = take.slice(offset, len);
}
// Safety:
// the created indices are in bounds
let mut df = if std::env::var("POLARS_VERT_PAR").is_ok() {
unsafe { self.take_unchecked_vectical(&take) }
} else {
unsafe { self.take_unchecked(&take) }
};
// Mark the first sort column as sorted
// if the column did not exists it is ok, because we sorted by an expression
// not present in the dataframe
let _ = df.apply(&first_by_column, |s| {
let mut s = s.clone();
if first_reverse {
s.set_sorted(IsSorted::Descending)
} else {
s.set_sorted(IsSorted::Ascending)
}
s
});
Ok(df)
}
/// Return a sorted clone of this `DataFrame`.
///
/// # Example
///
/// ```
/// # use polars_core::prelude::*;
/// fn sort_example(df: &DataFrame, reverse: bool) -> PolarsResult<DataFrame> {
/// df.sort(["a"], reverse)
/// }
///
/// fn sort_by_multiple_columns_example(df: &DataFrame) -> PolarsResult<DataFrame> {
/// df.sort(&["a", "b"], vec![false, true])
/// }
/// ```
pub fn sort(
&self,
by_column: impl IntoVec<String>,
reverse: impl IntoVec<bool>,
) -> PolarsResult<Self> {
let mut df = self.clone();
df.sort_in_place(by_column, reverse)?;
Ok(df)
}
/// Sort the `DataFrame` by a single column with extra options.
pub fn sort_with_options(&self, by_column: &str, options: SortOptions) -> PolarsResult<Self> {
let mut df = self.clone();
// a lot of indirection in both sorting and take
df.as_single_chunk_par();
let by_column = vec![df.column(by_column)?.clone()];
let reverse = vec![options.descending];
df.columns = df
.sort_impl(by_column, reverse, options.nulls_last, None)?
.columns;
Ok(df)
}
/// Replace a column with a `Series`.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let mut df: DataFrame = df!("Country" => &["United States", "China"],
/// "Area (km²)" => &[9_833_520, 9_596_961])?;
/// let s: Series = Series::new("Country", &["USA", "PRC"]);
///
/// assert!(df.replace("Nation", s.clone()).is_err());
/// assert!(df.replace("Country", s).is_ok());
/// # Ok::<(), PolarsError>(())
/// ```
pub fn replace<S: IntoSeries>(&mut self, column: &str, new_col: S) -> PolarsResult<&mut Self> {
self.apply(column, |_| new_col.into_series())
}
/// Replace or update a column. The difference between this method and [DataFrame::with_column]
/// is that now the value of `column: &str` determines the name of the column and not the name
/// of the `Series` passed to this method.
pub fn replace_or_add<S: IntoSeries>(
&mut self,
column: &str,
new_col: S,
) -> PolarsResult<&mut Self> {
let mut new_col = new_col.into_series();
new_col.rename(column);
self.with_column(new_col)
}
/// Replace column at index `idx` with a `Series`.
///
/// # Example
///
/// ```ignored
/// # use polars_core::prelude::*;
/// let s0 = Series::new("foo", &["ham", "spam", "egg"]);
/// let s1 = Series::new("ascii", &[70, 79, 79]);
/// let mut df = DataFrame::new(vec![s0, s1])?;
///
/// // Add 32 to get lowercase ascii values
/// df.replace_at_idx(1, df.select_at_idx(1).unwrap() + 32);
/// # Ok::<(), PolarsError>(())
/// ```
pub fn replace_at_idx<S: IntoSeries>(
&mut self,
idx: usize,
new_col: S,
) -> PolarsResult<&mut Self> {
let mut new_column = new_col.into_series();
if new_column.len() != self.height() {
return Err(PolarsError::ShapeMisMatch(
format!("Cannot replace Series at index {}. The shape of Series {} does not match that of the DataFrame {}",
idx, new_column.len(), self.height()
).into()));
};
if idx >= self.width() {
return Err(PolarsError::ComputeError(
format!(
"Column index: {} outside of DataFrame with {} columns",
idx,
self.width()
)
.into(),
));
}
let old_col = &mut self.columns[idx];
mem::swap(old_col, &mut new_column);
Ok(self)
}
/// Apply a closure to a column. This is the recommended way to do in place modification.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let s0 = Series::new("foo", &["ham", "spam", "egg"]);
/// let s1 = Series::new("names", &["Jean", "Claude", "van"]);
/// let mut df = DataFrame::new(vec![s0, s1])?;
///
/// fn str_to_len(str_val: &Series) -> Series {
/// str_val.utf8()
/// .unwrap()
/// .into_iter()
/// .map(|opt_name: Option<&str>| {
/// opt_name.map(|name: &str| name.len() as u32)
/// })
/// .collect::<UInt32Chunked>()
/// .into_series()
/// }
///
/// // Replace the names column by the length of the names.
/// df.apply("names", str_to_len);
/// # Ok::<(), PolarsError>(())
/// ```
/// Results in:
///
/// ```text
/// +--------+-------+
/// | foo | |
/// | --- | names |
/// | str | u32 |
/// +========+=======+
/// | "ham" | 4 |
/// +--------+-------+
/// | "spam" | 6 |
/// +--------+-------+
/// | "egg" | 3 |
/// +--------+-------+
/// ```
pub fn apply<F, S>(&mut self, name: &str, f: F) -> PolarsResult<&mut Self>
where
F: FnOnce(&Series) -> S,
S: IntoSeries,
{
let idx = self.check_name_to_idx(name)?;
self.apply_at_idx(idx, f)
}
/// Apply a closure to a column at index `idx`. This is the recommended way to do in place
/// modification.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let s0 = Series::new("foo", &["ham", "spam", "egg"]);
/// let s1 = Series::new("ascii", &[70, 79, 79]);
/// let mut df = DataFrame::new(vec![s0, s1])?;
///
/// // Add 32 to get lowercase ascii values
/// df.apply_at_idx(1, |s| s + 32);
/// # Ok::<(), PolarsError>(())
/// ```
/// Results in:
///
/// ```text
/// +--------+-------+
/// | foo | ascii |
/// | --- | --- |
/// | str | i32 |
/// +========+=======+
/// | "ham" | 102 |
/// +--------+-------+
/// | "spam" | 111 |
/// +--------+-------+
/// | "egg" | 111 |
/// +--------+-------+
/// ```
pub fn apply_at_idx<F, S>(&mut self, idx: usize, f: F) -> PolarsResult<&mut Self>
where
F: FnOnce(&Series) -> S,
S: IntoSeries,
{
let df_height = self.height();
let width = self.width();
let col = self.columns.get_mut(idx).ok_or_else(|| {
PolarsError::ComputeError(
format!("Column index: {idx} outside of DataFrame with {width} columns",).into(),
)
})?;
let name = col.name().to_string();
let new_col = f(col).into_series();
match new_col.len() {
1 => {
let new_col = new_col.new_from_index(0, df_height);
let _ = mem::replace(col, new_col);
}
len if (len == df_height) => {
let _ = mem::replace(col, new_col);
}
len => {
return Err(PolarsError::ShapeMisMatch(
format!(
"Result Series has shape {} where the DataFrame has height {}",
len,
self.height()
)
.into(),
));
}
}
// make sure the name remains the same after applying the closure
unsafe {
let col = self.columns.get_unchecked_mut(idx);
col.rename(&name);
}
Ok(self)
}
/// Apply a closure that may fail to a column at index `idx`. This is the recommended way to do in place
/// modification.
///
/// # Example
///
/// This is the idiomatic way to replace some values a column of a `DataFrame` given range of indexes.
///
/// ```rust
/// # use polars_core::prelude::*;
/// let s0 = Series::new("foo", &["ham", "spam", "egg", "bacon", "quack"]);
/// let s1 = Series::new("values", &[1, 2, 3, 4, 5]);
/// let mut df = DataFrame::new(vec![s0, s1])?;
///
/// let idx = vec![0, 1, 4];
///
/// df.try_apply("foo", |s| {
/// s.utf8()?
/// .set_at_idx_with(idx, |opt_val| opt_val.map(|string| format!("{}-is-modified", string)))
/// });
/// # Ok::<(), PolarsError>(())
/// ```
/// Results in:
///
/// ```text
/// +---------------------+--------+
/// | foo | values |
/// | --- | --- |
/// | str | i32 |
/// +=====================+========+
/// | "ham-is-modified" | 1 |
/// +---------------------+--------+
/// | "spam-is-modified" | 2 |
/// +---------------------+--------+
/// | "egg" | 3 |
/// +---------------------+--------+
/// | "bacon" | 4 |
/// +---------------------+--------+
/// | "quack-is-modified" | 5 |
/// +---------------------+--------+
/// ```
pub fn try_apply_at_idx<F, S>(&mut self, idx: usize, f: F) -> PolarsResult<&mut Self>
where
F: FnOnce(&Series) -> PolarsResult<S>,
S: IntoSeries,
{
let width = self.width();
let col = self.columns.get_mut(idx).ok_or_else(|| {
PolarsError::ComputeError(
format!("Column index: {idx} outside of DataFrame with {width} columns",).into(),
)
})?;
let name = col.name().to_string();
let _ = mem::replace(col, f(col).map(|s| s.into_series())?);
// make sure the name remains the same after applying the closure
unsafe {
let col = self.columns.get_unchecked_mut(idx);
col.rename(&name);
}
Ok(self)
}
/// Apply a closure that may fail to a column. This is the recommended way to do in place
/// modification.
///
/// # Example
///
/// This is the idiomatic way to replace some values a column of a `DataFrame` given a boolean mask.
///
/// ```rust
/// # use polars_core::prelude::*;
/// let s0 = Series::new("foo", &["ham", "spam", "egg", "bacon", "quack"]);
/// let s1 = Series::new("values", &[1, 2, 3, 4, 5]);
/// let mut df = DataFrame::new(vec![s0, s1])?;
///
/// // create a mask
/// let values = df.column("values")?;
/// let mask = values.lt_eq(1)? | values.gt_eq(5_i32)?;
///
/// df.try_apply("foo", |s| {
/// s.utf8()?
/// .set(&mask, Some("not_within_bounds"))
/// });
/// # Ok::<(), PolarsError>(())
/// ```
/// Results in:
///
/// ```text
/// +---------------------+--------+
/// | foo | values |
/// | --- | --- |
/// | str | i32 |
/// +=====================+========+
/// | "not_within_bounds" | 1 |
/// +---------------------+--------+
/// | "spam" | 2 |
/// +---------------------+--------+
/// | "egg" | 3 |
/// +---------------------+--------+
/// | "bacon" | 4 |
/// +---------------------+--------+
/// | "not_within_bounds" | 5 |
/// +---------------------+--------+
/// ```
pub fn try_apply<F, S>(&mut self, column: &str, f: F) -> PolarsResult<&mut Self>
where
F: FnOnce(&Series) -> PolarsResult<S>,
S: IntoSeries,
{
let idx = self
.find_idx_by_name(column)
.ok_or_else(|| PolarsError::NotFound(column.to_string().into()))?;
self.try_apply_at_idx(idx, f)
}
/// Slice the `DataFrame` along the rows.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Fruit" => &["Apple", "Grape", "Grape", "Fig", "Fig"],
/// "Color" => &["Green", "Red", "White", "White", "Red"])?;
/// let sl: DataFrame = df.slice(2, 3);
///
/// assert_eq!(sl.shape(), (3, 2));
/// println!("{}", sl);
/// # Ok::<(), PolarsError>(())
/// ```
/// Output:
/// ```text
/// shape: (3, 2)
/// +-------+-------+
/// | Fruit | Color |
/// | --- | --- |
/// | str | str |
/// +=======+=======+
/// | Grape | White |
/// +-------+-------+
/// | Fig | White |
/// +-------+-------+
/// | Fig | Red |
/// +-------+-------+
/// ```
#[must_use]
pub fn slice(&self, offset: i64, length: usize) -> Self {
if offset == 0 && length == self.height() {
return self.clone();
}
let col = self
.columns
.iter()
.map(|s| s.slice(offset, length))
.collect::<Vec<_>>();
DataFrame::new_no_checks(col)
}
#[must_use]
pub fn slice_par(&self, offset: i64, length: usize) -> Self {
if offset == 0 && length == self.height() {
return self.clone();
}
DataFrame::new_no_checks(self.apply_columns_par(&|s| s.slice(offset, length)))
}
#[must_use]
pub fn _slice_and_realloc(&self, offset: i64, length: usize) -> Self {
if offset == 0 && length == self.height() {
return self.clone();
}
DataFrame::new_no_checks(self.apply_columns(&|s| {
let mut out = s.slice(offset, length);
out.shrink_to_fit();
out
}))
}
/// Get the head of the `DataFrame`.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let countries: DataFrame =
/// df!("Rank by GDP (2021)" => &[1, 2, 3, 4, 5],
/// "Continent" => &["North America", "Asia", "Asia", "Europe", "Europe"],
/// "Country" => &["United States", "China", "Japan", "Germany", "United Kingdom"],
/// "Capital" => &["Washington", "Beijing", "Tokyo", "Berlin", "London"])?;
/// assert_eq!(countries.shape(), (5, 4));
///
/// println!("{}", countries.head(Some(3)));
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (3, 4)
/// +--------------------+---------------+---------------+------------+
/// | Rank by GDP (2021) | Continent | Country | Capital |
/// | --- | --- | --- | --- |
/// | i32 | str | str | str |
/// +====================+===============+===============+============+
/// | 1 | North America | United States | Washington |
/// +--------------------+---------------+---------------+------------+
/// | 2 | Asia | China | Beijing |
/// +--------------------+---------------+---------------+------------+
/// | 3 | Asia | Japan | Tokyo |
/// +--------------------+---------------+---------------+------------+
/// ```
#[must_use]
pub fn head(&self, length: Option<usize>) -> Self {
let col = self
.columns
.iter()
.map(|s| s.head(length))
.collect::<Vec<_>>();
DataFrame::new_no_checks(col)
}
/// Get the tail of the `DataFrame`.
///
/// # Example
///
/// ```rust
/// # use polars_core::prelude::*;
/// let countries: DataFrame =
/// df!("Rank (2021)" => &[105, 106, 107, 108, 109],
/// "Apple Price (€/kg)" => &[0.75, 0.70, 0.70, 0.65, 0.52],
/// "Country" => &["Kosovo", "Moldova", "North Macedonia", "Syria", "Turkey"])?;
/// assert_eq!(countries.shape(), (5, 3));
///
/// println!("{}", countries.tail(Some(2)));
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (2, 3)
/// +-------------+--------------------+---------+
/// | Rank (2021) | Apple Price (€/kg) | Country |
/// | --- | --- | --- |
/// | i32 | f64 | str |
/// +=============+====================+=========+
/// | 108 | 0.63 | Syria |
/// +-------------+--------------------+---------+
/// | 109 | 0.63 | Turkey |
/// +-------------+--------------------+---------+
/// ```
#[must_use]
pub fn tail(&self, length: Option<usize>) -> Self {
let col = self
.columns
.iter()
.map(|s| s.tail(length))
.collect::<Vec<_>>();
DataFrame::new_no_checks(col)
}
/// Iterator over the rows in this `DataFrame` as Arrow RecordBatches.
///
/// # Panics
///
/// Panics if the `DataFrame` that is passed is not rechunked.
///
/// This responsibility is left to the caller as we don't want to take mutable references here,
/// but we also don't want to rechunk here, as this operation is costly and would benefit the caller
/// as well.
pub fn iter_chunks(&self) -> RecordBatchIter {
RecordBatchIter {
columns: &self.columns,
idx: 0,
n_chunks: self.n_chunks(),
}
}
/// Iterator over the rows in this `DataFrame` as Arrow RecordBatches as physical values.
///
/// # Panics
///
/// Panics if the `DataFrame` that is passed is not rechunked.
///
/// This responsibility is left to the caller as we don't want to take mutable references here,
/// but we also don't want to rechunk here, as this operation is costly and would benefit the caller
/// as well.
pub fn iter_chunks_physical(&self) -> PhysRecordBatchIter<'_> {
PhysRecordBatchIter {
iters: self.columns.iter().map(|s| s.chunks().iter()).collect(),
}
}
/// Get a `DataFrame` with all the columns in reversed order.
#[must_use]
pub fn reverse(&self) -> Self {
let col = self.columns.iter().map(|s| s.reverse()).collect::<Vec<_>>();
DataFrame::new_no_checks(col)
}
/// Shift the values by a given period and fill the parts that will be empty due to this operation
/// with `Nones`.
///
/// See the method on [Series](../series/trait.SeriesTrait.html#method.shift) for more info on the `shift` operation.
#[must_use]
pub fn shift(&self, periods: i64) -> Self {
let col = self.apply_columns_par(&|s| s.shift(periods));
DataFrame::new_no_checks(col)
}
/// Replace None values with one of the following strategies:
/// * Forward fill (replace None with the previous value)
/// * Backward fill (replace None with the next value)
/// * Mean fill (replace None with the mean of the whole array)
/// * Min fill (replace None with the minimum of the whole array)
/// * Max fill (replace None with the maximum of the whole array)
///
/// See the method on [Series](../series/trait.SeriesTrait.html#method.fill_null) for more info on the `fill_null` operation.
pub fn fill_null(&self, strategy: FillNullStrategy) -> PolarsResult<Self> {
let col = self.try_apply_columns_par(&|s| s.fill_null(strategy))?;
Ok(DataFrame::new_no_checks(col))
}
/// Summary statistics for a DataFrame. Only summarizes numeric datatypes at the moment and returns nulls for non numeric datatypes.
/// Try in keep output similar to pandas
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("categorical" => &["d","e","f"],
/// "numeric" => &[1, 2, 3],
/// "object" => &["a", "b", "c"])?;
/// assert_eq!(df1.shape(), (3, 3));
///
/// let df2: DataFrame = df1.describe(None);
/// assert_eq!(df2.shape(), (8, 4));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (8, 4)
/// ┌──────────┬─────────────┬─────────┬────────┐
/// │ describe ┆ categorical ┆ numeric ┆ object │
/// │ --- ┆ --- ┆ --- ┆ --- │
/// │ str ┆ f64 ┆ f64 ┆ f64 │
/// ╞══════════╪═════════════╪═════════╪════════╡
/// │ count ┆ 3.0 ┆ 3.0 ┆ 3.0 │
/// ├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
/// │ mean ┆ null ┆ 2.0 ┆ null │
/// ├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
/// │ std ┆ null ┆ 1.0 ┆ null │
/// ├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
/// │ min ┆ null ┆ 1.0 ┆ null │
/// ├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
/// │ 25% ┆ null ┆ 1.5 ┆ null │
/// ├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
/// │ 50% ┆ null ┆ 2.0 ┆ null │
/// ├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
/// │ 75% ┆ null ┆ 2.5 ┆ null │
/// ├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
/// │ max ┆ null ┆ 3.0 ┆ null │
/// └──────────┴─────────────┴─────────┴────────┘
/// ```
#[must_use]
#[cfg(feature = "describe")]
pub fn describe(&self, percentiles: Option<&[f64]>) -> Self {
fn describe_cast(df: &DataFrame) -> DataFrame {
let mut columns: Vec<Series> = vec![];
for s in df.columns.iter() {
columns.push(s.cast(&DataType::Float64).expect("cast to float failed"));
}
DataFrame::new(columns).unwrap()
}
fn count(df: &DataFrame) -> DataFrame {
let columns = df.apply_columns_par(&|s| Series::new(s.name(), [s.len() as IdxSize]));
DataFrame::new_no_checks(columns)
}
let percentiles = percentiles.unwrap_or(&[0.25, 0.5, 0.75]);
let mut headers: Vec<String> = vec![
"count".to_string(),
"mean".to_string(),
"std".to_string(),
"min".to_string(),
];
let mut tmp: Vec<DataFrame> = vec![
describe_cast(&count(self)),
describe_cast(&self.mean()),
describe_cast(&self.std(1)),
describe_cast(&self.min()),
];
for p in percentiles {
tmp.push(describe_cast(
&self
.quantile(*p, QuantileInterpolOptions::Linear)
.expect("quantile failed"),
));
headers.push(format!("{}%", *p * 100.0));
}
// Keep order same as pandas
tmp.push(describe_cast(&self.max()));
headers.push("max".to_string());
let mut summary = concat_df_unchecked(&tmp);
summary
.insert_at_idx(0, Series::new("describe", headers))
.expect("insert of header failed");
summary
}
/// Aggregate the columns to their maximum values.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Die n°1" => &[1, 3, 1, 5, 6],
/// "Die n°2" => &[3, 2, 3, 5, 3])?;
/// assert_eq!(df1.shape(), (5, 2));
///
/// let df2: DataFrame = df1.max();
/// assert_eq!(df2.shape(), (1, 2));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (1, 2)
/// +---------+---------+
/// | Die n°1 | Die n°2 |
/// | --- | --- |
/// | i32 | i32 |
/// +=========+=========+
/// | 6 | 5 |
/// +---------+---------+
/// ```
#[must_use]
pub fn max(&self) -> Self {
let columns = self.apply_columns_par(&|s| s.max_as_series());
DataFrame::new_no_checks(columns)
}
/// Aggregate the columns to their standard deviation values.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Die n°1" => &[1, 3, 1, 5, 6],
/// "Die n°2" => &[3, 2, 3, 5, 3])?;
/// assert_eq!(df1.shape(), (5, 2));
///
/// let df2: DataFrame = df1.std(1);
/// assert_eq!(df2.shape(), (1, 2));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (1, 2)
/// +-------------------+--------------------+
/// | Die n°1 | Die n°2 |
/// | --- | --- |
/// | f64 | f64 |
/// +===================+====================+
/// | 2.280350850198276 | 1.0954451150103321 |
/// +-------------------+--------------------+
/// ```
#[must_use]
pub fn std(&self, ddof: u8) -> Self {
let columns = self.apply_columns_par(&|s| s.std_as_series(ddof));
DataFrame::new_no_checks(columns)
}
/// Aggregate the columns to their variation values.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Die n°1" => &[1, 3, 1, 5, 6],
/// "Die n°2" => &[3, 2, 3, 5, 3])?;
/// assert_eq!(df1.shape(), (5, 2));
///
/// let df2: DataFrame = df1.var(1);
/// assert_eq!(df2.shape(), (1, 2));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (1, 2)
/// +---------+---------+
/// | Die n°1 | Die n°2 |
/// | --- | --- |
/// | f64 | f64 |
/// +=========+=========+
/// | 5.2 | 1.2 |
/// +---------+---------+
/// ```
#[must_use]
pub fn var(&self, ddof: u8) -> Self {
let columns = self.apply_columns_par(&|s| s.var_as_series(ddof));
DataFrame::new_no_checks(columns)
}
/// Aggregate the columns to their minimum values.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Die n°1" => &[1, 3, 1, 5, 6],
/// "Die n°2" => &[3, 2, 3, 5, 3])?;
/// assert_eq!(df1.shape(), (5, 2));
///
/// let df2: DataFrame = df1.min();
/// assert_eq!(df2.shape(), (1, 2));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (1, 2)
/// +---------+---------+
/// | Die n°1 | Die n°2 |
/// | --- | --- |
/// | i32 | i32 |
/// +=========+=========+
/// | 1 | 2 |
/// +---------+---------+
/// ```
#[must_use]
pub fn min(&self) -> Self {
let columns = self.apply_columns_par(&|s| s.min_as_series());
DataFrame::new_no_checks(columns)
}
/// Aggregate the columns to their sum values.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Die n°1" => &[1, 3, 1, 5, 6],
/// "Die n°2" => &[3, 2, 3, 5, 3])?;
/// assert_eq!(df1.shape(), (5, 2));
///
/// let df2: DataFrame = df1.sum();
/// assert_eq!(df2.shape(), (1, 2));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (1, 2)
/// +---------+---------+
/// | Die n°1 | Die n°2 |
/// | --- | --- |
/// | i32 | i32 |
/// +=========+=========+
/// | 16 | 16 |
/// +---------+---------+
/// ```
#[must_use]
pub fn sum(&self) -> Self {
let columns = self.apply_columns_par(&|s| s.sum_as_series());
DataFrame::new_no_checks(columns)
}
/// Aggregate the columns to their mean values.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Die n°1" => &[1, 3, 1, 5, 6],
/// "Die n°2" => &[3, 2, 3, 5, 3])?;
/// assert_eq!(df1.shape(), (5, 2));
///
/// let df2: DataFrame = df1.mean();
/// assert_eq!(df2.shape(), (1, 2));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (1, 2)
/// +---------+---------+
/// | Die n°1 | Die n°2 |
/// | --- | --- |
/// | f64 | f64 |
/// +=========+=========+
/// | 3.2 | 3.2 |
/// +---------+---------+
/// ```
#[must_use]
pub fn mean(&self) -> Self {
let columns = self.apply_columns_par(&|s| s.mean_as_series());
DataFrame::new_no_checks(columns)
}
/// Aggregate the columns to their median values.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df1: DataFrame = df!("Die n°1" => &[1, 3, 1, 5, 6],
/// "Die n°2" => &[3, 2, 3, 5, 3])?;
/// assert_eq!(df1.shape(), (5, 2));
///
/// let df2: DataFrame = df1.median();
/// assert_eq!(df2.shape(), (1, 2));
/// println!("{}", df2);
/// # Ok::<(), PolarsError>(())
/// ```
///
/// Output:
///
/// ```text
/// shape: (1, 2)
/// +---------+---------+
/// | Die n°1 | Die n°2 |
/// | --- | --- |
/// | i32 | i32 |
/// +=========+=========+
/// | 3 | 3 |
/// +---------+---------+
/// ```
#[must_use]
pub fn median(&self) -> Self {
let columns = self.apply_columns_par(&|s| s.median_as_series());
DataFrame::new_no_checks(columns)
}
/// Aggregate the columns to their quantile values.
pub fn quantile(&self, quantile: f64, interpol: QuantileInterpolOptions) -> PolarsResult<Self> {
let columns = self.try_apply_columns_par(&|s| s.quantile_as_series(quantile, interpol))?;
Ok(DataFrame::new_no_checks(columns))
}
/// Aggregate the column horizontally to their min values.
#[cfg(feature = "zip_with")]
#[cfg_attr(docsrs, doc(cfg(feature = "zip_with")))]
pub fn hmin(&self) -> PolarsResult<Option<Series>> {
let min_fn = |acc: &Series, s: &Series| {
let mask = acc.lt(s)? & acc.is_not_null() | s.is_null();
acc.zip_with(&mask, s)
};
match self.columns.len() {
0 => Ok(None),
1 => Ok(Some(self.columns[0].clone())),
2 => min_fn(&self.columns[0], &self.columns[1]).map(Some),
_ => {
// the try_reduce_with is a bit slower in parallelism,
// but I don't think it matters here as we parallelize over columns, not over elements
POOL.install(|| {
self.columns
.par_iter()
.map(|s| Ok(Cow::Borrowed(s)))
.try_reduce_with(|l, r| min_fn(&l, &r).map(Cow::Owned))
// we can unwrap the option, because we are certain there is a column
// we started this operation on 3 columns
.unwrap()
.map(|cow| Some(cow.into_owned()))
})
}
}
}
/// Aggregate the column horizontally to their max values.
#[cfg(feature = "zip_with")]
#[cfg_attr(docsrs, doc(cfg(feature = "zip_with")))]
pub fn hmax(&self) -> PolarsResult<Option<Series>> {
let max_fn = |acc: &Series, s: &Series| {
let mask = acc.gt(s)? & acc.is_not_null() | s.is_null();
acc.zip_with(&mask, s)
};
match self.columns.len() {
0 => Ok(None),
1 => Ok(Some(self.columns[0].clone())),
2 => max_fn(&self.columns[0], &self.columns[1]).map(Some),
_ => {
// the try_reduce_with is a bit slower in parallelism,
// but I don't think it matters here as we parallelize over columns, not over elements
POOL.install(|| {
self.columns
.par_iter()
.map(|s| Ok(Cow::Borrowed(s)))
.try_reduce_with(|l, r| max_fn(&l, &r).map(Cow::Owned))
// we can unwrap the option, because we are certain there is a column
// we started this operation on 3 columns
.unwrap()
.map(|cow| Some(cow.into_owned()))
})
}
}
}
/// Aggregate the column horizontally to their sum values.
pub fn hsum(&self, none_strategy: NullStrategy) -> PolarsResult<Option<Series>> {
let sum_fn =
|acc: &Series, s: &Series, none_strategy: NullStrategy| -> PolarsResult<Series> {
let mut acc = acc.clone();
let mut s = s.clone();
if let NullStrategy::Ignore = none_strategy {
// if has nulls
if acc.has_validity() {
acc = acc.fill_null(FillNullStrategy::Zero)?;
}
if s.has_validity() {
s = s.fill_null(FillNullStrategy::Zero)?;
}
}
Ok(&acc + &s)
};
match self.columns.len() {
0 => Ok(None),
1 => Ok(Some(self.columns[0].clone())),
2 => sum_fn(&self.columns[0], &self.columns[1], none_strategy).map(Some),
_ => {
// the try_reduce_with is a bit slower in parallelism,
// but I don't think it matters here as we parallelize over columns, not over elements
POOL.install(|| {
self.columns
.par_iter()
.map(|s| Ok(Cow::Borrowed(s)))
.try_reduce_with(|l, r| sum_fn(&l, &r, none_strategy).map(Cow::Owned))
// we can unwrap the option, because we are certain there is a column
// we started this operation on 3 columns
.unwrap()
.map(|cow| Some(cow.into_owned()))
})
}
}
}
/// Aggregate the column horizontally to their mean values.
pub fn hmean(&self, none_strategy: NullStrategy) -> PolarsResult<Option<Series>> {
match self.columns.len() {
0 => Ok(None),
1 => Ok(Some(self.columns[0].clone())),
_ => {
let columns = self
.columns
.iter()
.cloned()
.filter(|s| {
let dtype = s.dtype();
dtype.is_numeric() || matches!(dtype, DataType::Boolean)
})
.collect();
let numeric_df = DataFrame::new_no_checks(columns);
let sum = || numeric_df.hsum(none_strategy);
let null_count = || {
numeric_df
.columns
.par_iter()
.map(|s| s.is_null().cast(&DataType::UInt32).unwrap())
.reduce_with(|l, r| &l + &r)
// we can unwrap the option, because we are certain there is a column
// we started this operation on 2 columns
.unwrap()
};
let (sum, null_count) = POOL.install(|| rayon::join(sum, null_count));
let sum = sum?;
// value lengths: len - null_count
let value_length: UInt32Chunked =
(numeric_df.width().sub(&null_count)).u32().unwrap().clone();
// make sure that we do not divide by zero
// by replacing with None
let value_length = value_length
.set(&value_length.equal(0), None)?
.into_series()
.cast(&DataType::Float64)?;
Ok(sum.map(|sum| &sum / &value_length))
}
}
}
/// Pipe different functions/ closure operations that work on a DataFrame together.
pub fn pipe<F, B>(self, f: F) -> PolarsResult<B>
where
F: Fn(DataFrame) -> PolarsResult<B>,
{
f(self)
}
/// Pipe different functions/ closure operations that work on a DataFrame together.
pub fn pipe_mut<F, B>(&mut self, f: F) -> PolarsResult<B>
where
F: Fn(&mut DataFrame) -> PolarsResult<B>,
{
f(self)
}
/// Pipe different functions/ closure operations that work on a DataFrame together.
pub fn pipe_with_args<F, B, Args>(self, f: F, args: Args) -> PolarsResult<B>
where
F: Fn(DataFrame, Args) -> PolarsResult<B>,
{
f(self, args)
}
/// Drop duplicate rows from a `DataFrame`.
/// *This fails when there is a column of type List in DataFrame*
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df = df! {
/// "flt" => [1., 1., 2., 2., 3., 3.],
/// "int" => [1, 1, 2, 2, 3, 3, ],
/// "str" => ["a", "a", "b", "b", "c", "c"]
/// }?;
///
/// println!("{}", df.drop_duplicates(true, None)?);
/// # Ok::<(), PolarsError>(())
/// ```
/// Returns
///
/// ```text
/// +-----+-----+-----+
/// | flt | int | str |
/// | --- | --- | --- |
/// | f64 | i32 | str |
/// +=====+=====+=====+
/// | 1 | 1 | "a" |
/// +-----+-----+-----+
/// | 2 | 2 | "b" |
/// +-----+-----+-----+
/// | 3 | 3 | "c" |
/// +-----+-----+-----+
/// ```
#[deprecated(note = "use DataFrame::unique")]
pub fn drop_duplicates(
&self,
maintain_order: bool,
subset: Option<&[String]>,
) -> PolarsResult<Self> {
match maintain_order {
true => self.unique_stable(subset, UniqueKeepStrategy::First),
false => self.unique(subset, UniqueKeepStrategy::First),
}
}
/// Drop duplicate rows from a `DataFrame`.
/// *This fails when there is a column of type List in DataFrame*
///
/// Stable means that the order is maintained. This has a higher cost than an unstable distinct.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df = df! {
/// "flt" => [1., 1., 2., 2., 3., 3.],
/// "int" => [1, 1, 2, 2, 3, 3, ],
/// "str" => ["a", "a", "b", "b", "c", "c"]
/// }?;
///
/// println!("{}", df.unique_stable(None, UniqueKeepStrategy::First)?);
/// # Ok::<(), PolarsError>(())
/// ```
/// Returns
///
/// ```text
/// +-----+-----+-----+
/// | flt | int | str |
/// | --- | --- | --- |
/// | f64 | i32 | str |
/// +=====+=====+=====+
/// | 1 | 1 | "a" |
/// +-----+-----+-----+
/// | 2 | 2 | "b" |
/// +-----+-----+-----+
/// | 3 | 3 | "c" |
/// +-----+-----+-----+
/// ```
pub fn unique_stable(
&self,
subset: Option<&[String]>,
keep: UniqueKeepStrategy,
) -> PolarsResult<DataFrame> {
self.unique_impl(true, subset, keep)
}
/// Unstable distinct. See [`DataFrame::unique_stable`].
pub fn unique(
&self,
subset: Option<&[String]>,
keep: UniqueKeepStrategy,
) -> PolarsResult<DataFrame> {
self.unique_impl(false, subset, keep)
}
fn unique_impl(
&self,
maintain_order: bool,
subset: Option<&[String]>,
keep: UniqueKeepStrategy,
) -> PolarsResult<Self> {
use UniqueKeepStrategy::*;
let names = match &subset {
Some(s) => s.iter().map(|s| &**s).collect(),
None => self.get_column_names(),
};
let columns = match (keep, maintain_order) {
(First, true) => {
let gb = self.groupby_stable(names)?;
let groups = gb.get_groups();
self.apply_columns_par(&|s| unsafe { s.agg_first(groups) })
}
(Last, true) => {
// maintain order by last values, so the sorted groups are not correct as they
// are sorted by the first value
let gb = self.groupby(names)?;
let groups = gb.get_groups();
let last_idx: NoNull<IdxCa> = groups
.iter()
.map(|g| match g {
GroupsIndicator::Idx((_first, idx)) => idx[idx.len() - 1],
GroupsIndicator::Slice([first, len]) => first + len,
})
.collect();
let last_idx = last_idx.sort(false);
return Ok(unsafe { self.take_unchecked(&last_idx) });
}
(First, false) => {
let gb = self.groupby(names)?;
let groups = gb.get_groups();
self.apply_columns_par(&|s| unsafe { s.agg_first(groups) })
}
(Last, false) => {
let gb = self.groupby(names)?;
let groups = gb.get_groups();
self.apply_columns_par(&|s| unsafe { s.agg_last(groups) })
}
};
Ok(DataFrame::new_no_checks(columns))
}
/// Get a mask of all the unique rows in the `DataFrame`.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Company" => &["Apple", "Microsoft"],
/// "ISIN" => &["US0378331005", "US5949181045"])?;
/// let ca: ChunkedArray<BooleanType> = df.is_unique()?;
///
/// assert!(ca.all());
/// # Ok::<(), PolarsError>(())
/// ```
pub fn is_unique(&self) -> PolarsResult<BooleanChunked> {
let gb = self.groupby(self.get_column_names())?;
let groups = gb.take_groups();
Ok(is_unique_helper(
groups,
self.height() as IdxSize,
true,
false,
))
}
/// Get a mask of all the duplicated rows in the `DataFrame`.
///
/// # Example
///
/// ```no_run
/// # use polars_core::prelude::*;
/// let df: DataFrame = df!("Company" => &["Alphabet", "Alphabet"],
/// "ISIN" => &["US02079K3059", "US02079K1079"])?;
/// let ca: ChunkedArray<BooleanType> = df.is_duplicated()?;
///
/// assert!(!ca.all());
/// # Ok::<(), PolarsError>(())
/// ```
pub fn is_duplicated(&self) -> PolarsResult<BooleanChunked> {
let gb = self.groupby(self.get_column_names())?;
let groups = gb.take_groups();
Ok(is_unique_helper(
groups,
self.height() as IdxSize,
false,
true,
))
}
/// Create a new `DataFrame` that shows the null counts per column.
#[must_use]
pub fn null_count(&self) -> Self {
let cols = self
.columns
.iter()
.map(|s| Series::new(s.name(), &[s.null_count() as IdxSize]))
.collect();
Self::new_no_checks(cols)
}
/// Hash and combine the row values
#[cfg(feature = "row_hash")]
pub fn hash_rows(
&mut self,
hasher_builder: Option<RandomState>,
) -> PolarsResult<UInt64Chunked> {
let dfs = split_df(self, POOL.current_num_threads())?;
let (cas, _) = df_rows_to_hashes_threaded(&dfs, hasher_builder)?;
let mut iter = cas.into_iter();
let mut acc_ca = iter.next().unwrap();
for ca in iter {
acc_ca.append(&ca);
}
Ok(acc_ca.rechunk())
}
/// Get the supertype of the columns in this DataFrame
pub fn get_supertype(&self) -> Option<PolarsResult<DataType>> {
self.columns
.iter()
.map(|s| Ok(s.dtype().clone()))
.reduce(|acc, b| try_get_supertype(&acc?, &b.unwrap()))
}
#[cfg(feature = "chunked_ids")]
#[doc(hidden)]
//// Take elements by a slice of [`ChunkId`]s.
/// # Safety
/// Does not do any bound checks.
/// `sorted` indicates if the chunks are sorted.
#[doc(hidden)]
pub unsafe fn _take_chunked_unchecked_seq(&self, idx: &[ChunkId], sorted: IsSorted) -> Self {
let cols = self.apply_columns(&|s| s._take_chunked_unchecked(idx, sorted));
DataFrame::new_no_checks(cols)
}
#[cfg(feature = "chunked_ids")]
//// Take elements by a slice of optional [`ChunkId`]s.
/// # Safety
/// Does not do any bound checks.
#[doc(hidden)]
pub unsafe fn _take_opt_chunked_unchecked_seq(&self, idx: &[Option<ChunkId>]) -> Self {
let cols = self.apply_columns(&|s| match s.dtype() {
DataType::Utf8 => s._take_opt_chunked_unchecked_threaded(idx, true),
_ => s._take_opt_chunked_unchecked(idx),
});
DataFrame::new_no_checks(cols)
}
#[cfg(feature = "chunked_ids")]
pub(crate) unsafe fn take_chunked_unchecked(&self, idx: &[ChunkId], sorted: IsSorted) -> Self {
let cols = self.apply_columns_par(&|s| match s.dtype() {
DataType::Utf8 => s._take_chunked_unchecked_threaded(idx, sorted, true),
_ => s._take_chunked_unchecked(idx, sorted),
});
DataFrame::new_no_checks(cols)
}
#[cfg(feature = "chunked_ids")]
pub(crate) unsafe fn take_opt_chunked_unchecked(&self, idx: &[Option<ChunkId>]) -> Self {
let cols = self.apply_columns_par(&|s| match s.dtype() {
DataType::Utf8 => s._take_opt_chunked_unchecked_threaded(idx, true),
_ => s._take_opt_chunked_unchecked(idx),
});
DataFrame::new_no_checks(cols)
}
/// Be careful with allowing threads when calling this in a large hot loop
/// every thread split may be on rayon stack and lead to SO
#[doc(hidden)]
pub unsafe fn _take_unchecked_slice(&self, idx: &[IdxSize], allow_threads: bool) -> Self {
self._take_unchecked_slice2(idx, allow_threads, IsSorted::Not)
}
#[doc(hidden)]
pub unsafe fn _take_unchecked_slice2(
&self,
idx: &[IdxSize],
allow_threads: bool,
sorted: IsSorted,
) -> Self {
#[cfg(debug_assertions)]
{
if idx.len() > 2 {
match sorted {
IsSorted::Ascending => {
assert!(idx[0] <= idx[idx.len() - 1]);
}
IsSorted::Descending => {
assert!(idx[0] >= idx[idx.len() - 1]);
}
_ => {}
}
}
}
let ptr = idx.as_ptr() as *mut IdxSize;
let len = idx.len();
// create a temporary vec. we will not drop it.
let mut ca = IdxCa::from_vec("", Vec::from_raw_parts(ptr, len, len));
ca.set_sorted2(sorted);
let out = self.take_unchecked_impl(&ca, allow_threads);
// ref count of buffers should be one because we dropped all allocations
let arr = {
let arr_ref = std::mem::take(&mut ca.chunks).pop().unwrap();
arr_ref
.as_any()
.downcast_ref::<PrimitiveArray<IdxSize>>()
.unwrap()
.clone()
};
// the only owned heap allocation is the `Vec` we created and must not be dropped
let _ = std::mem::ManuallyDrop::new(arr.into_mut().right().unwrap());
out
}
source§impl ChunkedArray<ListType>
impl ChunkedArray<ListType>
sourcepub fn amortized_iter(
&self
) -> AmortizedListIter<'_, impl Iterator<Item = Option<ArrayBox>> + '_>
pub fn amortized_iter(
&self
) -> AmortizedListIter<'_, impl Iterator<Item = Option<ArrayBox>> + '_>
This is an iterator over a ListChunked that save allocations.
A Series is:
1. Arc
The ArrayRef we indicated with 3. will be updated during iteration. The Series will be pinned in memory, saving an allocation for
- Arc<..>
- Vec<…>
Warning
Though memory safe in the sense that it will not read unowned memory, UB, or memory leaks
this function still needs precautions. The returned should never be cloned or taken longer
than a single iteration, as every call on next
of the iterator will change the contents of
that Series.
Examples found in repository?
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
fn equal(&self, rhs: &ListChunked) -> BooleanChunked {
self.amortized_iter()
.zip(rhs.amortized_iter())
.map(|(left, right)| match (left, right) {
(None, None) => true,
(Some(l), Some(r)) => l.as_ref().series_equal_missing(r.as_ref()),
_ => false,
})
.collect_trusted()
}
fn not_equal(&self, rhs: &ListChunked) -> BooleanChunked {
self.amortized_iter()
.zip(rhs.amortized_iter())
.map(|(left, right)| {
let out = match (left, right) {
(None, None) => true,
(Some(l), Some(r)) => l.as_ref().series_equal_missing(r.as_ref()),
_ => false,
};
!out
})
.collect_trusted()
}
More examples
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
pub fn apply_amortized<'a, F>(&'a self, mut f: F) -> Self
where
F: FnMut(UnstableSeries<'a>) -> Series,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = self.null_count() == 0;
let mut ca: ListChunked = self
.amortized_iter()
.map(|opt_v| {
opt_v.map(|v| {
let out = f(v);
if out.is_empty() {
fast_explode = false;
}
out
})
})
.collect_trusted();
ca.rename(self.name());
if fast_explode {
ca.set_fast_explode();
}
ca
}
pub fn try_apply_amortized<'a, F>(&'a self, mut f: F) -> PolarsResult<Self>
where
F: FnMut(UnstableSeries<'a>) -> PolarsResult<Series>,
{
if self.is_empty() {
return Ok(self.clone());
}
let mut fast_explode = self.null_count() == 0;
let mut ca: ListChunked = self
.amortized_iter()
.map(|opt_v| {
opt_v
.map(|v| {
let out = f(v);
if let Ok(out) = &out {
if out.is_empty() {
fast_explode = false
}
};
out
})
.transpose()
})
.collect::<PolarsResult<_>>()?;
ca.rename(self.name());
if fast_explode {
ca.set_fast_explode();
}
Ok(ca)
}
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
fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked> {
// We check implicitly cast to supertype here
match other.dtype() {
DataType::List(dt) => {
let st = try_get_supertype(self.dtype(), dt)?;
if &st != self.dtype() {
let left = self.cast(&st)?;
let right = other.cast(&DataType::List(Box::new(st)))?;
return left.is_in(&right);
}
let mut ca: BooleanChunked = if self.len() == 1 && other.len() != 1 {
let value = self.get(0);
other
.list()?
.amortized_iter()
.map(|opt_s| {
opt_s.map(|s| {
let ca = s.as_ref().unpack::<T>().unwrap();
ca.into_iter().any(|a| a == value)
}) == Some(true)
})
.collect_trusted()
} else {
self.into_iter()
.zip(other.list()?.amortized_iter())
.map(|(value, series)| match (value, series) {
(val, Some(series)) => {
let ca = series.as_ref().unpack::<T>().unwrap();
ca.into_iter().any(|a| a == val)
}
_ => false,
})
.collect_trusted()
};
ca.rename(self.name());
Ok(ca)
}
_ => {
// first make sure that the types are equal
let st = try_get_supertype(self.dtype(), other.dtype())?;
if self.dtype() != other.dtype() {
let left = self.cast(&st)?;
let right = other.cast(&st)?;
return left.is_in(&right);
}
// now that the types are equal, we coerce every 32 bit array to u32
// and every 64 bit array to u64 (including floats)
// this allows hashing them and greatly reduces the number of code paths.
match self.dtype() {
DataType::UInt64 | DataType::Int64 | DataType::Float64 => unsafe {
is_in_helper::<T, u64>(self, other)
},
DataType::UInt32 | DataType::Int32 | DataType::Float32 => unsafe {
is_in_helper::<T, u32>(self, other)
},
DataType::UInt8 | DataType::Int8 => unsafe {
is_in_helper::<T, u8>(self, other)
},
DataType::UInt16 | DataType::Int16 => unsafe {
is_in_helper::<T, u16>(self, other)
},
_ => Err(PolarsError::ComputeError(
format!(
"Data type {:?} not supported in is_in operation",
self.dtype()
)
.into(),
)),
}
}
}
.map(|mut ca| {
ca.rename(self.name());
ca
})
}
}
impl IsIn for Utf8Chunked {
fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked> {
match other.dtype() {
#[cfg(feature = "dtype-categorical")]
DataType::List(dt) if matches!(&**dt, DataType::Categorical(_)) => {
if let DataType::Categorical(Some(rev_map)) = &**dt {
let opt_val = self.get(0);
let other = other.list()?;
match opt_val {
None => {
let mut ca: BooleanChunked = other
.amortized_iter()
.map(|opt_s| {
opt_s.map(|s| s.as_ref().null_count() > 0) == Some(true)
})
.collect_trusted();
ca.rename(self.name());
Ok(ca)
}
Some(value) => {
match rev_map.find(value) {
// all false
None => Ok(BooleanChunked::full(self.name(), false, other.len())),
Some(idx) => {
let mut ca: BooleanChunked = other
.amortized_iter()
.map(|opt_s| {
opt_s.map(|s| {
let s = s.as_ref().to_physical_repr();
let ca = s.as_ref().u32().unwrap();
if ca.null_count() == 0 {
ca.into_no_null_iter().any(|a| a == idx)
} else {
ca.into_iter().any(|a| a == Some(idx))
}
}) == Some(true)
})
.collect_trusted();
ca.rename(self.name());
Ok(ca)
}
}
}
}
} else {
unreachable!()
}
}
DataType::List(dt) if DataType::Utf8 == **dt => {
let mut ca: BooleanChunked = if self.len() == 1 && other.len() != 1 {
let value = self.get(0);
other
.list()?
.amortized_iter()
.map(|opt_s| {
opt_s.map(|s| {
let ca = s.as_ref().unpack::<Utf8Type>().unwrap();
ca.into_iter().any(|a| a == value)
}) == Some(true)
})
.collect_trusted()
} else {
self.into_iter()
.zip(other.list()?.amortized_iter())
.map(|(value, series)| match (value, series) {
(val, Some(series)) => {
let ca = series.as_ref().unpack::<Utf8Type>().unwrap();
ca.into_iter().any(|a| a == val)
}
_ => false,
})
.collect_trusted()
};
ca.rename(self.name());
Ok(ca)
}
DataType::Utf8 => {
let mut set = HashSet::with_capacity(other.len());
let other = other.utf8()?;
other.downcast_iter().for_each(|iter| {
iter.into_iter().for_each(|opt_val| {
set.insert(opt_val);
})
});
let mut ca: BooleanChunked = self
.into_iter()
.map(|opt_val| set.contains(&opt_val))
.collect_trusted();
ca.rename(self.name());
Ok(ca)
}
_ => Err(PolarsError::SchemaMisMatch(
format!(
"cannot do is_in operation with left a dtype: {:?} and right a dtype {:?}",
self.dtype(),
other.dtype()
)
.into(),
)),
}
.map(|mut ca| {
ca.rename(self.name());
ca
})
}
}
#[cfg(feature = "dtype-binary")]
impl IsIn for BinaryChunked {
fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked> {
match other.dtype() {
DataType::List(dt) if DataType::Binary == **dt => {
let mut ca: BooleanChunked = if self.len() == 1 && other.len() != 1 {
let value = self.get(0);
other
.list()?
.amortized_iter()
.map(|opt_b| {
opt_b.map(|s| {
let ca = s.as_ref().unpack::<BinaryType>().unwrap();
ca.into_iter().any(|a| a == value)
}) == Some(true)
})
.collect_trusted()
} else {
self.into_iter()
.zip(other.list()?.amortized_iter())
.map(|(value, series)| match (value, series) {
(val, Some(series)) => {
let ca = series.as_ref().unpack::<BinaryType>().unwrap();
ca.into_iter().any(|a| a == val)
}
_ => false,
})
.collect_trusted()
};
ca.rename(self.name());
Ok(ca)
}
DataType::Binary => {
let mut set = HashSet::with_capacity(other.len());
let other = other.binary()?;
other.downcast_iter().for_each(|iter| {
iter.into_iter().for_each(|opt_val| {
set.insert(opt_val);
})
});
let mut ca: BooleanChunked = self
.into_iter()
.map(|opt_val| set.contains(&opt_val))
.collect_trusted();
ca.rename(self.name());
Ok(ca)
}
_ => Err(PolarsError::SchemaMisMatch(
format!(
"cannot do is_in operation with left a dtype: {:?} and right a dtype {:?}",
self.dtype(),
other.dtype()
)
.into(),
)),
}
.map(|mut ca| {
ca.rename(self.name());
ca
})
}
}
impl IsIn for BooleanChunked {
fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked> {
match other.dtype() {
DataType::List(dt) if self.dtype() == &**dt => {
let mut ca: BooleanChunked = if self.len() == 1 && other.len() != 1 {
let value = self.get(0);
// safety: we know the iterators len
unsafe {
other
.list()?
.amortized_iter()
.map(|opt_s| {
opt_s.map(|s| {
let ca = s.as_ref().unpack::<BooleanType>().unwrap();
ca.into_iter().any(|a| a == value)
}) == Some(true)
})
.trust_my_length(other.len())
.collect_trusted()
}
} else {
self.into_iter()
.zip(other.list()?.amortized_iter())
.map(|(value, series)| match (value, series) {
(val, Some(series)) => {
let ca = series.as_ref().unpack::<BooleanType>().unwrap();
ca.into_iter().any(|a| a == val)
}
_ => false,
})
.collect_trusted()
};
ca.rename(self.name());
Ok(ca)
}
DataType::Boolean => {
let other = other.bool().unwrap();
let has_true = other.any();
let has_false = !other.all();
Ok(self.apply(|v| if v { has_true } else { has_false }))
}
_ => Err(PolarsError::SchemaMisMatch(
format!(
"cannot do is_in operation with left a dtype: {:?} and right a dtype {:?}",
self.dtype(),
other.dtype()
)
.into(),
)),
}
.map(|mut ca| {
ca.rename(self.name());
ca
})
}
sourcepub fn apply_amortized<'a, F>(&'a self, f: F) -> Selfwhere
F: FnMut(UnstableSeries<'a>) -> Series,
pub fn apply_amortized<'a, F>(&'a self, f: F) -> Selfwhere
F: FnMut(UnstableSeries<'a>) -> Series,
Apply a closure F
elementwise.
pub fn try_apply_amortized<'a, F>(&'a self, f: F) -> PolarsResult<Self>where
F: FnMut(UnstableSeries<'a>) -> PolarsResult<Series>,
source§impl ChunkedArray<ListType>
impl ChunkedArray<ListType>
sourcepub fn set_fast_explode(&mut self)
pub fn set_fast_explode(&mut self)
Examples found in repository?
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
fn apply<F>(&'a self, f: F) -> Self
where
F: Fn(Series) -> Series + Copy,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = true;
let mut function = |s: Series| {
let out = f(s);
if out.is_empty() {
fast_explode = false;
}
out
};
let mut ca: ListChunked = apply!(self, &mut function);
if fast_explode {
ca.set_fast_explode()
}
ca
}
fn try_apply<F>(&'a self, f: F) -> PolarsResult<Self>
where
F: Fn(Series) -> PolarsResult<Series> + Copy,
{
if self.is_empty() {
return Ok(self.clone());
}
let mut fast_explode = true;
let mut function = |s: Series| {
let out = f(s);
if let Ok(out) = &out {
if out.is_empty() {
fast_explode = false;
}
}
out
};
let ca: PolarsResult<ListChunked> = try_apply!(self, &mut function);
let mut ca = ca?;
if fast_explode {
ca.set_fast_explode()
}
Ok(ca)
}
fn apply_on_opt<F>(&'a self, f: F) -> Self
where
F: Fn(Option<Series>) -> Option<Series> + Copy,
{
if self.is_empty() {
return self.clone();
}
self.into_iter().map(f).collect_trusted()
}
/// Apply a closure elementwise. The closure gets the index of the element as first argument.
fn apply_with_idx<F>(&'a self, f: F) -> Self
where
F: Fn((usize, Series)) -> Series + Copy,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = true;
let mut function = |(idx, s)| {
let out = f((idx, s));
if out.is_empty() {
fast_explode = false;
}
out
};
let mut ca: ListChunked = apply_enumerate!(self, function);
if fast_explode {
ca.set_fast_explode()
}
ca
}
/// Apply a closure elementwise. The closure gets the index of the element as first argument.
fn apply_with_idx_on_opt<F>(&'a self, f: F) -> Self
where
F: Fn((usize, Option<Series>)) -> Option<Series> + Copy,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = true;
let function = |(idx, s)| {
let out = f((idx, s));
if let Some(out) = &out {
if out.is_empty() {
fast_explode = false;
}
}
out
};
let mut ca: ListChunked = self.into_iter().enumerate().map(function).collect_trusted();
if fast_explode {
ca.set_fast_explode()
}
ca
}
More examples
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
fn reshape_fast_path(name: &str, s: &Series) -> Series {
let chunks = match s.dtype() {
#[cfg(feature = "dtype-struct")]
DataType::Struct(_) => {
vec![Box::new(array_to_unit_list(s.array_ref(0).clone())) as ArrayRef]
}
_ => s
.chunks()
.iter()
.map(|arr| Box::new(array_to_unit_list(arr.clone())) as ArrayRef)
.collect::<Vec<_>>(),
};
let mut ca = ListChunked::from_chunks(name, chunks);
ca.set_inner_dtype(s.dtype().clone());
ca.set_fast_explode();
ca.into_series()
}
impl Series {
/// Convert the values of this Series to a ListChunked with a length of 1,
/// So a Series of:
/// `[1, 2, 3]` becomes `[[1, 2, 3]]`
pub fn to_list(&self) -> PolarsResult<ListChunked> {
let s = self.rechunk();
let values = s.array_ref(0);
let offsets = vec![0i64, values.len() as i64];
let inner_type = self.dtype();
let data_type = ListArray::<i64>::default_datatype(inner_type.to_physical().to_arrow());
// Safety:
// offsets are correct;
let arr = unsafe {
ListArray::new(
data_type,
Offsets::new_unchecked(offsets).into(),
values.clone(),
None,
)
};
let name = self.name();
let mut ca = ListChunked::from_chunks(name, vec![Box::new(arr)]);
if self.dtype() != &self.dtype().to_physical() {
ca.to_logical(inner_type.clone())
}
ca.set_fast_explode();
Ok(ca)
}
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
pub fn finish(&mut self) -> ListChunked {
let slf = std::mem::take(self);
if slf.builder.is_empty() {
ListChunked::full_null_with_dtype(&slf.name, 0, &slf.dtype.unwrap_or(DataType::Null))
} else {
let dtype = slf.dtype.map(|dt| dt.to_physical().to_arrow());
let arr = slf.builder.finish(dtype.as_ref()).unwrap();
let dtype = DataType::from(arr.data_type());
let mut ca = ListChunked::from_chunks("", vec![Box::new(arr)]);
if self.fast_explode {
ca.set_fast_explode();
}
ca.field = Arc::new(Field::new(&slf.name, dtype));
ca
}
}
}
pub struct AnonymousOwnedListBuilder {
name: String,
builder: AnonymousBuilder<'static>,
owned: Vec<Series>,
inner_dtype: Option<DataType>,
fast_explode: bool,
}
impl Default for AnonymousOwnedListBuilder {
fn default() -> Self {
Self::new("", 0, None)
}
}
impl ListBuilderTrait for AnonymousOwnedListBuilder {
fn append_series(&mut self, s: &Series) {
if s.is_empty() {
self.append_empty();
} else {
// Safety
// we deref a raw pointer with a lifetime that is not static
// it is safe because we also clone Series (Arc +=1) and therefore the &dyn Arrays
// will not be dropped until the owned series are dropped
unsafe {
match s.dtype() {
#[cfg(feature = "dtype-struct")]
DataType::Struct(_) => {
self.builder.push(&*(&**s.array_ref(0) as *const dyn Array))
}
_ => {
self.builder
.push_multiple(&*(s.chunks().as_ref() as *const [ArrayRef]));
}
}
}
// this make sure that the underlying ArrayRef's are not dropped
self.owned.push(s.clone());
}
}
#[inline]
fn append_null(&mut self) {
self.builder.push_null()
}
fn finish(&mut self) -> ListChunked {
let slf = std::mem::take(self);
if slf.builder.is_empty() {
// not really empty, there were empty null list added probably e.g. []
let real_length = slf.builder.offsets().len() - 1;
if real_length > 0 {
let dtype = slf.inner_dtype.unwrap_or(NULL_DTYPE).to_arrow();
let array = new_null_array(dtype.clone(), real_length);
let dtype = ListArray::<i64>::default_datatype(dtype);
let array = ListArray::new(dtype, slf.builder.take_offsets().into(), array, None);
ListChunked::from_chunks(&slf.name, vec![Box::new(array)])
} else {
ListChunked::full_null_with_dtype(
&slf.name,
0,
&slf.inner_dtype.unwrap_or(DataType::Null),
)
}
} else {
let inner_dtype = slf.inner_dtype.map(|dt| dt.to_physical().to_arrow());
let arr = slf.builder.finish(inner_dtype.as_ref()).unwrap();
let dtype = DataType::from(arr.data_type());
let mut ca = ListChunked::from_chunks("", vec![Box::new(arr)]);
if self.fast_explode {
ca.set_fast_explode();
}
ca.field = Arc::new(Field::new(&slf.name, dtype));
ca
}
}
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
pub fn apply_amortized<'a, F>(&'a self, mut f: F) -> Self
where
F: FnMut(UnstableSeries<'a>) -> Series,
{
if self.is_empty() {
return self.clone();
}
let mut fast_explode = self.null_count() == 0;
let mut ca: ListChunked = self
.amortized_iter()
.map(|opt_v| {
opt_v.map(|v| {
let out = f(v);
if out.is_empty() {
fast_explode = false;
}
out
})
})
.collect_trusted();
ca.rename(self.name());
if fast_explode {
ca.set_fast_explode();
}
ca
}
pub fn try_apply_amortized<'a, F>(&'a self, mut f: F) -> PolarsResult<Self>
where
F: FnMut(UnstableSeries<'a>) -> PolarsResult<Series>,
{
if self.is_empty() {
return Ok(self.clone());
}
let mut fast_explode = self.null_count() == 0;
let mut ca: ListChunked = self
.amortized_iter()
.map(|opt_v| {
opt_v
.map(|v| {
let out = f(v);
if let Ok(out) = &out {
if out.is_empty() {
fast_explode = false
}
};
out
})
.transpose()
})
.collect::<PolarsResult<_>>()?;
ca.rename(self.name());
if fast_explode {
ca.set_fast_explode();
}
Ok(ca)
}
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
fn finish(&mut self) -> ListChunked {
let values_builder = std::mem::take(&mut self.values_builder);
let offsets = std::mem::take(&mut self.offsets);
let ca = values_builder.finish();
let obj_arr = ca.downcast_chunks().get(0).unwrap().clone();
let mut pe = create_extension(obj_arr.into_iter_cloned());
// Safety:
// this is safe because we just created the PolarsExtension
// meaning that the sentinel is heap allocated and the dereference of the
// pointer does not fail
unsafe { pe.set_to_series_fn::<T>() };
let extension_array = Box::new(pe.take_and_forget()) as ArrayRef;
let extension_dtype = extension_array.data_type();
let data_type = ListArray::<i64>::default_datatype(extension_dtype.clone());
// Safety:
// offsets are monotonically increasing
let arr = unsafe {
Box::new(ListArray::<i64>::new(
data_type,
Offsets::new_unchecked(offsets).into(),
extension_array,
None,
)) as ArrayRef
};
let mut listarr = ListChunked::from_chunks(ca.name(), vec![arr]);
if self.fast_explode {
listarr.set_fast_explode()
}
listarr
}
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
unsafe fn agg_list(&self, groups: &GroupsProxy) -> Series {
let ca = self.rechunk();
match groups {
GroupsProxy::Idx(groups) => {
let mut can_fast_explode = true;
let arr = ca.downcast_iter().next().unwrap();
let values = arr.values();
let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1);
let mut length_so_far = 0i64;
offsets.push(length_so_far);
let mut list_values = Vec::<T::Native>::with_capacity(self.len());
groups.iter().for_each(|(_, idx)| {
let idx_len = idx.len();
if idx_len == 0 {
can_fast_explode = false;
}
length_so_far += idx_len as i64;
// Safety:
// group tuples are in bounds
{
list_values.extend(idx.iter().map(|idx| {
debug_assert!((*idx as usize) < values.len());
*values.get_unchecked(*idx as usize)
}));
// Safety:
// we know that offsets has allocated enough slots
offsets.push_unchecked(length_so_far);
}
});
let validity = if arr.null_count() > 0 {
let old_validity = arr.validity().unwrap();
let mut validity = MutableBitmap::from_len_set(list_values.len());
let mut count = 0;
groups.iter().for_each(|(_, idx)| {
for i in idx {
if !old_validity.get_bit_unchecked(*i as usize) {
validity.set_bit_unchecked(count, false)
}
count += 1;
}
});
Some(validity.into())
} else {
None
};
let array =
PrimitiveArray::new(T::get_dtype().to_arrow(), list_values.into(), validity);
let data_type = ListArray::<i64>::default_datatype(T::get_dtype().to_arrow());
// Safety:
// offsets are monotonically increasing
let arr = ListArray::<i64>::new(
data_type,
Offsets::new_unchecked(offsets).into(),
Box::new(array),
None,
);
let mut ca = ListChunked::from_chunks(self.name(), vec![Box::new(arr)]);
if can_fast_explode {
ca.set_fast_explode()
}
ca.into()
}
GroupsProxy::Slice { groups, .. } => {
let mut can_fast_explode = true;
let arr = ca.downcast_iter().next().unwrap();
let values = arr.values();
let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1);
let mut length_so_far = 0i64;
offsets.push(length_so_far);
let mut list_values = Vec::<T::Native>::with_capacity(self.len());
groups.iter().for_each(|&[first, len]| {
if len == 0 {
can_fast_explode = false;
}
length_so_far += len as i64;
list_values.extend_from_slice(&values[first as usize..(first + len) as usize]);
{
// Safety:
// we know that offsets has allocated enough slots
offsets.push_unchecked(length_so_far);
}
});
let validity = if arr.null_count() > 0 {
let old_validity = arr.validity().unwrap();
let mut validity = MutableBitmap::from_len_set(list_values.len());
let mut count = 0;
groups.iter().for_each(|[first, len]| {
for i in *first..(*first + *len) {
if !old_validity.get_bit_unchecked(i as usize) {
validity.set_bit_unchecked(count, false)
}
count += 1;
}
});
Some(validity.into())
} else {
None
};
let array =
PrimitiveArray::new(T::get_dtype().to_arrow(), list_values.into(), validity);
let data_type = ListArray::<i64>::default_datatype(T::get_dtype().to_arrow());
let arr = ListArray::<i64>::new(
data_type,
Offsets::new_unchecked(offsets).into(),
Box::new(array),
None,
);
let mut ca = ListChunked::from_chunks(self.name(), vec![Box::new(arr)]);
if can_fast_explode {
ca.set_fast_explode()
}
ca.into()
}
}
}
}
impl AggList for BooleanChunked {
unsafe fn agg_list(&self, groups: &GroupsProxy) -> Series {
match groups {
GroupsProxy::Idx(groups) => {
let mut builder =
ListBooleanChunkedBuilder::new(self.name(), groups.len(), self.len());
for idx in groups.all().iter() {
let ca = { self.take_unchecked(idx.into()) };
builder.append(&ca)
}
builder.finish().into_series()
}
GroupsProxy::Slice { groups, .. } => {
let mut builder =
ListBooleanChunkedBuilder::new(self.name(), groups.len(), self.len());
for [first, len] in groups {
let ca = self.slice(*first as i64, *len as usize);
builder.append(&ca)
}
builder.finish().into_series()
}
}
}
}
impl AggList for Utf8Chunked {
unsafe fn agg_list(&self, groups: &GroupsProxy) -> Series {
match groups {
GroupsProxy::Idx(groups) => {
let mut builder =
ListUtf8ChunkedBuilder::new(self.name(), groups.len(), self.len());
for idx in groups.all().iter() {
let ca = { self.take_unchecked(idx.into()) };
builder.append(&ca)
}
builder.finish().into_series()
}
GroupsProxy::Slice { groups, .. } => {
let mut builder =
ListUtf8ChunkedBuilder::new(self.name(), groups.len(), self.len());
for [first, len] in groups {
let ca = self.slice(*first as i64, *len as usize);
builder.append(&ca)
}
builder.finish().into_series()
}
}
}
}
#[cfg(feature = "dtype-binary")]
impl AggList for BinaryChunked {
unsafe fn agg_list(&self, groups: &GroupsProxy) -> Series {
match groups {
GroupsProxy::Idx(groups) => {
let mut builder =
ListBinaryChunkedBuilder::new(self.name(), groups.len(), self.len());
for idx in groups.all().iter() {
let ca = { self.take_unchecked(idx.into()) };
builder.append(&ca)
}
builder.finish().into_series()
}
GroupsProxy::Slice { groups, .. } => {
let mut builder =
ListBinaryChunkedBuilder::new(self.name(), groups.len(), self.len());
for [first, len] in groups {
let ca = self.slice(*first as i64, *len as usize);
builder.append(&ca)
}
builder.finish().into_series()
}
}
}
}
fn agg_list_list<F: Fn(&ListChunked, bool, &mut Vec<i64>, &mut i64, &mut Vec<ArrayRef>) -> bool>(
ca: &ListChunked,
groups_len: usize,
func: F,
) -> Series {
let can_fast_explode = true;
let mut offsets = Vec::<i64>::with_capacity(groups_len + 1);
let mut length_so_far = 0i64;
offsets.push(length_so_far);
let mut list_values = Vec::with_capacity(groups_len);
let can_fast_explode = func(
ca,
can_fast_explode,
&mut offsets,
&mut length_so_far,
&mut list_values,
);
if groups_len == 0 {
list_values.push(ca.chunks[0].slice(0, 0))
}
let arrays = list_values.iter().map(|arr| &**arr).collect::<Vec<_>>();
let list_values: ArrayRef = arrow::compute::concatenate::concatenate(&arrays).unwrap();
let data_type = ListArray::<i64>::default_datatype(list_values.data_type().clone());
// Safety:
// offsets are monotonically increasing
let arr = unsafe {
Box::new(ListArray::<i64>::new(
data_type,
Offsets::new_unchecked(offsets).into(),
list_values,
None,
)) as ArrayRef
};
let mut listarr = ListChunked::from_chunks(ca.name(), vec![arr]);
if can_fast_explode {
listarr.set_fast_explode()
}
listarr.into_series()
}
impl AggList for ListChunked {
unsafe fn agg_list(&self, groups: &GroupsProxy) -> Series {
match groups {
GroupsProxy::Idx(groups) => {
let func = |ca: &ListChunked,
mut can_fast_explode: bool,
offsets: &mut Vec<i64>,
length_so_far: &mut i64,
list_values: &mut Vec<ArrayRef>| {
groups.iter().for_each(|(_, idx)| {
let idx_len = idx.len();
if idx_len == 0 {
can_fast_explode = false;
}
*length_so_far += idx_len as i64;
// Safety:
// group tuples are in bounds
{
let mut s = ca.take_unchecked(idx.into());
let arr = s.chunks.pop().unwrap();
list_values.push(arr);
// Safety:
// we know that offsets has allocated enough slots
offsets.push_unchecked(*length_so_far);
}
});
can_fast_explode
};
agg_list_list(self, groups.len(), func)
}
GroupsProxy::Slice { groups, .. } => {
let func = |ca: &ListChunked,
mut can_fast_explode: bool,
offsets: &mut Vec<i64>,
length_so_far: &mut i64,
list_values: &mut Vec<ArrayRef>| {
groups.iter().for_each(|&[first, len]| {
if len == 0 {
can_fast_explode = false;
}
*length_so_far += len as i64;
let mut s = ca.slice(first as i64, len as usize);
let arr = s.chunks.pop().unwrap();
list_values.push(arr);
{
// Safety:
// we know that offsets has allocated enough slots
offsets.push_unchecked(*length_so_far);
}
});
can_fast_explode
};
agg_list_list(self, groups.len(), func)
}
}
}
}
#[cfg(feature = "object")]
impl<T: PolarsObject> AggList for ObjectChunked<T> {
unsafe fn agg_list(&self, groups: &GroupsProxy) -> Series {
let mut can_fast_explode = true;
let mut offsets = Vec::<i64>::with_capacity(groups.len() + 1);
let mut length_so_far = 0i64;
offsets.push(length_so_far);
// we know that iterators length
let iter = {
groups
.iter()
.flat_map(|indicator| {
let (group_vals, len) = match indicator {
GroupsIndicator::Idx((_first, idx)) => {
// Safety:
// group tuples always in bounds
let group_vals = self.take_unchecked(idx.into());
(group_vals, idx.len() as IdxSize)
}
GroupsIndicator::Slice([first, len]) => {
let group_vals = _slice_from_offsets(self, first, len);
(group_vals, len)
}
};
if len == 0 {
can_fast_explode = false;
}
length_so_far += len as i64;
// Safety:
// we know that offsets has allocated enough slots
offsets.push_unchecked(length_so_far);
let arr = group_vals.downcast_iter().next().unwrap().clone();
arr.into_iter_cloned()
})
.trust_my_length(self.len())
};
let mut pe = create_extension(iter);
// Safety:
// this is safe because we just created the PolarsExtension
// meaning that the sentinel is heap allocated and the dereference of the
// pointer does not fail
pe.set_to_series_fn::<T>();
let extension_array = Box::new(pe.take_and_forget()) as ArrayRef;
let extension_dtype = extension_array.data_type();
let data_type = ListArray::<i64>::default_datatype(extension_dtype.clone());
// Safety:
// offsets are monotonically increasing
let arr = Box::new(ListArray::<i64>::new(
data_type,
Offsets::new_unchecked(offsets).into(),
extension_array,
None,
)) as ArrayRef;
let mut listarr = ListChunked::from_chunks(self.name(), vec![arr]);
if can_fast_explode {
listarr.set_fast_explode()
}
listarr.into_series()
}
sourcepub fn _can_fast_explode(&self) -> bool
pub fn _can_fast_explode(&self) -> bool
Examples found in repository?
60 61 62 63 64 65 66 67 68 69 70 71 72
pub fn append(&mut self, other: &Self) -> PolarsResult<()> {
let dtype = merge_dtypes(self.dtype(), other.dtype())?;
self.field = Arc::new(Field::new(self.name(), dtype));
let len = self.len();
self.length += other.length;
new_chunks(&mut self.chunks, &other.chunks, len);
self.set_sorted2(IsSorted::Not);
if !other._can_fast_explode() {
self.unset_fast_explode()
}
Ok(())
}
More examples
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
fn explode_and_offsets(&self) -> PolarsResult<(Series, OffsetsBuffer<i64>)> {
// A list array's memory layout is actually already 'exploded', so we can just take the values array
// of the list. And we also return a slice of the offsets. This slice can be used to find the old
// list layout or indexes to expand the DataFrame in the same manner as the 'explode' operation
let ca = self.rechunk();
let listarr: &LargeListArray = ca
.downcast_iter()
.next()
.ok_or_else(|| PolarsError::NoData("cannot explode empty list".into()))?;
let offsets_buf = listarr.offsets().clone();
let offsets = listarr.offsets().as_slice();
let mut values = listarr.values().clone();
// all empty
if offsets[offsets.len() - 1] == 0 {
return Ok((
Series::new_empty(self.name(), &self.inner_dtype()),
OffsetsBuffer::new(),
));
}
let mut s = if ca._can_fast_explode() {
// ensure that the value array is sliced
// as a list only slices its offsets on a slice operation
// we only do this in fast-explode as for the other
// branch the offsets must coincide with the values.
if !offsets.is_empty() {
let start = offsets[0] as usize;
let len = offsets[offsets.len() - 1] as usize - start;
// safety:
// we are in bounds
values = unsafe { values.slice_unchecked(start, len) };
}
Series::try_from((self.name(), values)).unwrap()
} else {
// during tests
// test that this code branch is not hit with list arrays that could be fast exploded
#[cfg(test)]
{
let mut last = offsets[0];
let mut has_empty = false;
for &o in &offsets[1..] {
if o == last {
has_empty = true;
}
last = o;
}
if !has_empty && offsets[0] == 0 {
panic!("could have fast exploded")
}
}
let values = Series::try_from((self.name(), values)).unwrap();
values.explode_by_offsets(offsets)
};
debug_assert_eq!(s.name(), self.name());
// make sure we restore the logical type
match self.inner_dtype() {
#[cfg(feature = "dtype-categorical")]
DataType::Categorical(rev_map) => {
let cats = s.u32().unwrap().clone();
// safety:
// rev_map is from same array, so we are still in bounds
s = unsafe {
CategoricalChunked::from_cats_and_rev_map_unchecked(cats, rev_map.unwrap())
.into_series()
};
}
#[cfg(feature = "dtype-date")]
DataType::Date => s = s.into_date(),
#[cfg(feature = "dtype-datetime")]
DataType::Datetime(tu, tz) => s = s.into_datetime(tu, tz),
#[cfg(feature = "dtype-duration")]
DataType::Duration(tu) => s = s.into_duration(tu),
#[cfg(feature = "dtype-time")]
DataType::Time => s = s.into_time(),
_ => {}
}
Ok((s, offsets_buf))
}
sourcepub fn to_logical(&mut self, inner_dtype: DataType)
pub fn to_logical(&mut self, inner_dtype: DataType)
Examples found in repository?
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
pub fn to_list(&self) -> PolarsResult<ListChunked> {
let s = self.rechunk();
let values = s.array_ref(0);
let offsets = vec![0i64, values.len() as i64];
let inner_type = self.dtype();
let data_type = ListArray::<i64>::default_datatype(inner_type.to_physical().to_arrow());
// Safety:
// offsets are correct;
let arr = unsafe {
ListArray::new(
data_type,
Offsets::new_unchecked(offsets).into(),
values.clone(),
None,
)
};
let name = self.name();
let mut ca = ListChunked::from_chunks(name, vec![Box::new(arr)]);
if self.dtype() != &self.dtype().to_physical() {
ca.to_logical(inner_type.clone())
}
ca.set_fast_explode();
Ok(ca)
}
source§impl<T> ChunkedArray<ObjectType<T>>where
T: PolarsObject,
impl<T> ChunkedArray<ObjectType<T>>where
T: PolarsObject,
pub fn new_from_vec(name: &str, v: Vec<T>) -> Self
object
only.source§impl<T> ChunkedArray<ObjectType<T>>where
T: PolarsObject,
impl<T> ChunkedArray<ObjectType<T>>where
T: PolarsObject,
sourcepub unsafe fn get_object_unchecked(
&self,
index: usize
) -> Option<&dyn PolarsObjectSafe>
Available on crate feature object
only.
pub unsafe fn get_object_unchecked(
&self,
index: usize
) -> Option<&dyn PolarsObjectSafe>
object
only.Get a hold to an object that can be formatted or downcasted via the Any trait.
Safety
No bounds checks
Examples found in repository?
More examples
sourcepub fn get_object(&self, index: usize) -> Option<&dyn PolarsObjectSafe>
Available on crate feature object
only.
pub fn get_object(&self, index: usize) -> Option<&dyn PolarsObjectSafe>
object
only.Get a hold to an object that can be formatted or downcasted via the Any trait.
Examples found in repository?
More examples
source§impl<T> ChunkedArray<T>where
T: PolarsNumericType,
Standard: Distribution<T::Native>,
impl<T> ChunkedArray<T>where
T: PolarsNumericType,
Standard: Distribution<T::Native>,
source§impl<T> ChunkedArray<T>where
T: PolarsDataType,
ChunkedArray<T>: ChunkTake,
impl<T> ChunkedArray<T>where
T: PolarsDataType,
ChunkedArray<T>: ChunkTake,
sourcepub fn sample_n(
&self,
n: usize,
with_replacement: bool,
shuffle: bool,
seed: Option<u64>
) -> PolarsResult<Self>
Available on crate feature random
only.
pub fn sample_n(
&self,
n: usize,
with_replacement: bool,
shuffle: bool,
seed: Option<u64>
) -> PolarsResult<Self>
random
only.Sample n datapoints from this ChunkedArray.
sourcepub fn sample_frac(
&self,
frac: f64,
with_replacement: bool,
shuffle: bool,
seed: Option<u64>
) -> PolarsResult<Self>
Available on crate feature random
only.
pub fn sample_frac(
&self,
frac: f64,
with_replacement: bool,
shuffle: bool,
seed: Option<u64>
) -> PolarsResult<Self>
random
only.Sample a fraction between 0.0-1.0 of this ChunkedArray.
source§impl<T> ChunkedArray<T>where
T: PolarsNumericType,
T::Native: Float,
impl<T> ChunkedArray<T>where
T: PolarsNumericType,
T::Native: Float,
sourcepub fn rand_normal(
name: &str,
length: usize,
mean: f64,
std_dev: f64
) -> PolarsResult<Self>
Available on crate feature random
only.
pub fn rand_normal(
name: &str,
length: usize,
mean: f64,
std_dev: f64
) -> PolarsResult<Self>
random
only.Create ChunkedArray
with samples from a Normal distribution.
sourcepub fn rand_standard_normal(name: &str, length: usize) -> Self
Available on crate feature random
only.
pub fn rand_standard_normal(name: &str, length: usize) -> Self
random
only.Create ChunkedArray
with samples from a Standard Normal distribution.
source§impl ChunkedArray<BooleanType>
impl ChunkedArray<BooleanType>
sourcepub fn rand_bernoulli(name: &str, length: usize, p: f64) -> PolarsResult<Self>
Available on crate feature random
only.
pub fn rand_bernoulli(name: &str, length: usize, p: f64) -> PolarsResult<Self>
random
only.Create ChunkedArray
with samples from a Bernoulli distribution.
source§impl ChunkedArray<Utf8Type>
impl ChunkedArray<Utf8Type>
pub fn hex_decode(&self, strict: Option<bool>) -> PolarsResult<Utf8Chunked>
pub fn hex_encode(&self) -> Utf8Chunked
pub fn base64_decode(&self, strict: Option<bool>) -> PolarsResult<Utf8Chunked>
pub fn base64_encode(&self) -> Utf8Chunked
source§impl<T: PolarsDataType> ChunkedArray<T>
impl<T: PolarsDataType> ChunkedArray<T>
sourcepub fn set_sorted(&mut self, reverse: bool)
pub fn set_sorted(&mut self, reverse: bool)
Set the ‘sorted’ bit meta info.
Examples found in repository?
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
fn new_from_index(&self, index: usize, length: usize) -> ChunkedArray<T> {
let mut out = impl_chunk_expand!(self, length, index);
out.set_sorted(false);
out
}
}
impl ChunkExpandAtIndex<BooleanType> for BooleanChunked {
fn new_from_index(&self, index: usize, length: usize) -> BooleanChunked {
let mut out = impl_chunk_expand!(self, length, index);
out.set_sorted(false);
out
}
}
impl ChunkExpandAtIndex<Utf8Type> for Utf8Chunked {
fn new_from_index(&self, index: usize, length: usize) -> Utf8Chunked {
let mut out = impl_chunk_expand!(self, length, index);
out.set_sorted(false);
out
}
More examples
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
pub fn with_row_count(&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(false);
columns.push(ca.into_series());
columns.extend_from_slice(&self.columns);
DataFrame::new(columns)
}
/// Add a row count in place.
pub fn with_row_count_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(false);
self.columns.insert(0, ca.into_series());
self
}
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
pub fn explode_impl(&self, mut columns: Vec<Series>) -> PolarsResult<DataFrame> {
let mut df = self.clone();
if self.height() == 0 {
for s in &columns {
df.with_column(s.explode()?)?;
}
return Ok(df);
}
columns.sort_by(|sa, sb| {
self.check_name_to_idx(sa.name())
.expect("checked above")
.partial_cmp(&self.check_name_to_idx(sb.name()).expect("checked above"))
.expect("cmp usize -> Ordering")
});
// first remove all the exploded columns
for s in &columns {
df = df.drop(s.name())?;
}
for (i, s) in columns.iter().enumerate() {
// Safety:
// offsets don't have indices exceeding Series length.
if let Ok((exploded, offsets)) = get_exploded(s) {
let col_idx = self.check_name_to_idx(s.name())?;
// expand all the other columns based the exploded first column
if i == 0 {
let row_idx = offsets_to_indexes(offsets.as_slice(), exploded.len());
let mut row_idx = IdxCa::from_vec("", row_idx);
row_idx.set_sorted(false);
// Safety
// We just created indices that are in bounds.
df = unsafe { df.take_unchecked(&row_idx) };
}
if exploded.len() == df.height() || df.width() == 0 {
df.columns.insert(col_idx, exploded);
} else {
return Err(PolarsError::ShapeMisMatch(
format!("The exploded column(s) don't have the same length. Length DataFrame: {}. Length exploded column {}: {}", df.height(), exploded.name(), exploded.len()).into(),
));
}
} else {
return Err(PolarsError::InvalidOperation(
format!("cannot explode dtype: {:?}", s.dtype()).into(),
));
}
}
Ok(df)
}
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
fn sort_with_numeric<T>(
ca: &ChunkedArray<T>,
options: SortOptions,
order_default: fn(&T::Native, &T::Native) -> Ordering,
order_reverse: fn(&T::Native, &T::Native) -> Ordering,
) -> ChunkedArray<T>
where
T: PolarsNumericType,
{
sort_with_fast_path!(ca, options);
if !ca.has_validity() {
let mut vals = memcpy_values(ca);
sort_branch(
vals.as_mut_slice(),
options.descending,
order_default,
order_reverse,
);
let mut ca = ChunkedArray::from_vec(ca.name(), vals);
ca.set_sorted(options.descending);
ca
} else {
let null_count = ca.null_count();
let len = ca.len();
let mut vals = Vec::with_capacity(ca.len());
if !options.nulls_last {
let iter = std::iter::repeat(T::Native::default()).take(null_count);
vals.extend(iter);
}
ca.downcast_iter().for_each(|arr| {
let iter = arr.iter().filter_map(|v| v.copied());
vals.extend(iter);
});
let mut_slice = if options.nulls_last {
&mut vals[..len - null_count]
} else {
&mut vals[null_count..]
};
sort_branch(mut_slice, options.descending, order_default, order_reverse);
let mut ca: ChunkedArray<T> = if options.nulls_last {
vals.extend(std::iter::repeat(T::Native::default()).take(ca.null_count()));
let mut validity = MutableBitmap::with_capacity(len);
validity.extend_constant(len - null_count, true);
validity.extend_constant(null_count, false);
(
ca.name(),
PrimitiveArray::new(
T::get_dtype().to_arrow(),
vals.into(),
Some(validity.into()),
),
)
.into()
} else {
let mut validity = MutableBitmap::with_capacity(len);
validity.extend_constant(null_count, false);
validity.extend_constant(len - null_count, true);
(
ca.name(),
PrimitiveArray::new(
T::get_dtype().to_arrow(),
vals.into(),
Some(validity.into()),
),
)
.into()
};
ca.set_sorted(options.descending);
ca
}
}
fn argsort_numeric<T>(ca: &ChunkedArray<T>, options: SortOptions) -> IdxCa
where
T: PolarsNumericType,
{
let reverse = options.descending;
if ca.null_count() == 0 {
let mut vals = Vec::with_capacity(ca.len());
let mut count: IdxSize = 0;
ca.downcast_iter().for_each(|arr| {
let values = arr.values();
let iter = values.iter().map(|&v| {
let i = count;
count += 1;
(i, v)
});
vals.extend_trusted_len(iter);
});
argsort_no_nulls(vals.as_mut_slice(), reverse);
let out: NoNull<IdxCa> = vals.into_iter().map(|(idx, _v)| idx).collect_trusted();
let mut out = out.into_inner();
out.rename(ca.name());
out
} else {
let iter = ca
.downcast_iter()
.map(|arr| arr.iter().map(|opt| opt.copied()));
argsort::argsort(ca.name(), iter, options, ca.null_count(), ca.len())
}
}
#[cfg(feature = "sort_multiple")]
fn argsort_multiple_numeric<T: PolarsNumericType>(
ca: &ChunkedArray<T>,
other: &[Series],
reverse: &[bool],
) -> PolarsResult<IdxCa> {
args_validate(ca, other, reverse)?;
let mut count: IdxSize = 0;
let vals: Vec<_> = ca
.into_iter()
.map(|v| {
let i = count;
count += 1;
(i, v)
})
.collect_trusted();
argsort_multiple_impl(vals, other, reverse)
}
impl<T> ChunkSort<T> for ChunkedArray<T>
where
T: PolarsIntegerType,
T::Native: Default + Ord,
{
fn sort_with(&self, options: SortOptions) -> ChunkedArray<T> {
sort_with_numeric(self, options, order_default, order_reverse)
}
fn sort(&self, reverse: bool) -> ChunkedArray<T> {
self.sort_with(SortOptions {
descending: reverse,
..Default::default()
})
}
fn argsort(&self, options: SortOptions) -> IdxCa {
argsort_numeric(self, options)
}
#[cfg(feature = "sort_multiple")]
/// # Panics
///
/// This function is very opinionated.
/// We assume that all numeric `Series` are of the same type, if not it will panic
fn argsort_multiple(&self, other: &[Series], reverse: &[bool]) -> PolarsResult<IdxCa> {
argsort_multiple_numeric(self, other, reverse)
}
}
impl ChunkSort<Float32Type> for Float32Chunked {
fn sort_with(&self, options: SortOptions) -> Float32Chunked {
sort_with_numeric(self, options, order_default_flt, order_reverse_flt)
}
fn sort(&self, reverse: bool) -> Float32Chunked {
self.sort_with(SortOptions {
descending: reverse,
..Default::default()
})
}
fn argsort(&self, options: SortOptions) -> IdxCa {
argsort_numeric(self, options)
}
#[cfg(feature = "sort_multiple")]
/// # Panics
///
/// This function is very opinionated.
/// We assume that all numeric `Series` are of the same type, if not it will panic
fn argsort_multiple(&self, other: &[Series], reverse: &[bool]) -> PolarsResult<IdxCa> {
argsort_multiple_numeric(self, other, reverse)
}
}
impl ChunkSort<Float64Type> for Float64Chunked {
fn sort_with(&self, options: SortOptions) -> Float64Chunked {
sort_with_numeric(self, options, order_default_flt, order_reverse_flt)
}
fn sort(&self, reverse: bool) -> Float64Chunked {
self.sort_with(SortOptions {
descending: reverse,
..Default::default()
})
}
fn argsort(&self, options: SortOptions) -> IdxCa {
argsort_numeric(self, options)
}
#[cfg(feature = "sort_multiple")]
/// # Panics
///
/// This function is very opinionated.
/// We assume that all numeric `Series` are of the same type, if not it will panic
fn argsort_multiple(&self, other: &[Series], reverse: &[bool]) -> PolarsResult<IdxCa> {
argsort_multiple_numeric(self, other, reverse)
}
}
fn ordering_other_columns<'a>(
compare_inner: &'a [Box<dyn PartialOrdInner + 'a>],
reverse: &[bool],
idx_a: usize,
idx_b: usize,
) -> Ordering {
for (cmp, reverse) in compare_inner.iter().zip(reverse) {
// Safety:
// indices are in bounds
let ordering = unsafe { cmp.cmp_element_unchecked(idx_a, idx_b) };
match (ordering, reverse) {
(Ordering::Equal, _) => continue,
(_, true) => return ordering.reverse(),
_ => return ordering,
}
}
// all arrays/columns exhausted, ordering equal it is.
Ordering::Equal
}
impl ChunkSort<Utf8Type> for Utf8Chunked {
fn sort_with(&self, options: SortOptions) -> ChunkedArray<Utf8Type> {
sort_with_fast_path!(self, options);
let mut v: Vec<&str> = if self.null_count() > 0 {
Vec::from_iter(self.into_iter().flatten())
} else {
Vec::from_iter(self.into_no_null_iter())
};
sort_branch(
v.as_mut_slice(),
options.descending,
order_default,
order_reverse,
);
let mut values = Vec::<u8>::with_capacity(self.get_values_size());
let mut offsets = Vec::<i64>::with_capacity(self.len() + 1);
let mut length_so_far = 0i64;
offsets.push(length_so_far);
let len = self.len();
let null_count = self.null_count();
let mut ca: Self = match (null_count, options.nulls_last) {
(0, _) => {
for val in v {
values.extend_from_slice(val.as_bytes());
length_so_far = values.len() as i64;
offsets.push(length_so_far);
}
// Safety:
// we pass valid utf8
let ar = unsafe {
Utf8Array::from_data_unchecked_default(offsets.into(), values.into(), None)
};
(self.name(), ar).into()
}
(_, true) => {
for val in v {
values.extend_from_slice(val.as_bytes());
length_so_far = values.len() as i64;
offsets.push(length_so_far);
}
let mut validity = MutableBitmap::with_capacity(len);
validity.extend_constant(len - null_count, true);
validity.extend_constant(null_count, false);
offsets.extend(std::iter::repeat(length_so_far).take(null_count));
// Safety:
// we pass valid utf8
let ar = unsafe {
Utf8Array::from_data_unchecked_default(
offsets.into(),
values.into(),
Some(validity.into()),
)
};
(self.name(), ar).into()
}
(_, false) => {
let mut validity = MutableBitmap::with_capacity(len);
validity.extend_constant(null_count, false);
validity.extend_constant(len - null_count, true);
offsets.extend(std::iter::repeat(length_so_far).take(null_count));
for val in v {
values.extend_from_slice(val.as_bytes());
length_so_far = values.len() as i64;
offsets.push(length_so_far);
}
// Safety:
// we pass valid utf8
let ar = unsafe {
Utf8Array::from_data_unchecked_default(
offsets.into(),
values.into(),
Some(validity.into()),
)
};
(self.name(), ar).into()
}
};
ca.set_sorted(options.descending);
ca
}
sourcepub fn is_sorted2(&self) -> IsSorted
pub fn is_sorted2(&self) -> IsSorted
Examples found in repository?
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
unsafe fn take_unchecked(&self, idx: &IdxCa) -> PolarsResult<Series> {
let idx = if idx.chunks.len() > 1 {
Cow::Owned(idx.rechunk())
} else {
Cow::Borrowed(idx)
};
let mut out = ChunkTake::take_unchecked(&self.0, (&*idx).into());
if self.0.is_sorted() && (idx.is_sorted() || idx.is_sorted_reverse()) {
out.set_sorted2(idx.is_sorted2())
}
Ok(out.into_series())
}
More examples
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
fn reverse(&self) -> ChunkedArray<T> {
let mut out = if let Ok(slice) = self.cont_slice() {
let ca: NoNull<ChunkedArray<T>> = slice.iter().rev().copied().collect_trusted();
ca.into_inner()
} else {
self.into_iter().rev().collect_trusted()
};
out.rename(self.name());
match self.is_sorted2() {
IsSorted::Ascending => out.set_sorted2(IsSorted::Descending),
IsSorted::Descending => out.set_sorted2(IsSorted::Ascending),
_ => {}
}
out
}
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
fn min(&self) -> Option<T::Native> {
match self.is_sorted2() {
IsSorted::Ascending => {
self.first_non_null().and_then(|idx| {
// Safety:
// first_non_null returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Descending => {
self.last_non_null().and_then(|idx| {
// Safety:
// last returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::min_primitive)
.fold_first_(|acc, v| {
if matches!(compare_fn_nan_max(&acc, &v), Ordering::Less) {
acc
} else {
v
}
}),
}
}
fn max(&self) -> Option<T::Native> {
match self.is_sorted2() {
IsSorted::Ascending => {
self.last_non_null().and_then(|idx| {
// Safety:
// first_non_null returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Descending => {
self.first_non_null().and_then(|idx| {
// Safety:
// last returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::max_primitive)
.fold_first_(|acc, v| {
if matches!(compare_fn_nan_min(&acc, &v), Ordering::Greater) {
acc
} else {
v
}
}),
}
}
fn mean(&self) -> Option<f64> {
match self.dtype() {
DataType::Float64 => {
let len = (self.len() - self.null_count()) as f64;
self.sum().map(|v| v.to_f64().unwrap() / len)
}
_ => {
let null_count = self.null_count();
let len = self.len();
if null_count == len {
None
} else {
let mut acc = 0.0;
let len = (len - null_count) as f64;
for arr in self.downcast_iter() {
if arr.null_count() > 0 {
for v in arr.into_iter().flatten() {
// safety
// all these types can be coerced to f64
unsafe {
let val = v.to_f64().unwrap_unchecked();
acc += val
}
}
} else {
for v in arr.values().as_slice() {
// safety
// all these types can be coerced to f64
unsafe {
let val = v.to_f64().unwrap_unchecked();
acc += val
}
}
}
}
Some(acc / len)
}
}
}
}
}
/// helper
fn quantile_idx(
quantile: f64,
length: usize,
null_count: usize,
interpol: QuantileInterpolOptions,
) -> (i64, f64, i64) {
let mut base_idx = match interpol {
QuantileInterpolOptions::Nearest => {
(((length - null_count) as f64) * quantile + null_count as f64) as i64
}
QuantileInterpolOptions::Lower
| QuantileInterpolOptions::Midpoint
| QuantileInterpolOptions::Linear => {
(((length - null_count) as f64 - 1.0) * quantile + null_count as f64) as i64
}
QuantileInterpolOptions::Higher => {
(((length - null_count) as f64 - 1.0) * quantile + null_count as f64).ceil() as i64
}
};
base_idx = base_idx.clamp(0, (length - 1) as i64);
let float_idx = ((length - null_count) as f64 - 1.0) * quantile + null_count as f64;
let top_idx = f64::ceil(float_idx) as i64;
(base_idx, float_idx, top_idx)
}
/// helper
fn linear_interpol<T: Float>(bounds: &[Option<T>], idx: i64, float_idx: f64) -> Option<T> {
if bounds[0] == bounds[1] {
Some(bounds[0].unwrap())
} else {
let proportion: T = T::from(float_idx).unwrap() - T::from(idx).unwrap();
Some(proportion * (bounds[1].unwrap() - bounds[0].unwrap()) + bounds[0].unwrap())
}
}
impl<T> ChunkQuantile<f64> for ChunkedArray<T>
where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn quantile(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Option<f64>> {
if !(0.0..=1.0).contains(&quantile) {
return Err(PolarsError::ComputeError(
"quantile should be between 0.0 and 1.0".into(),
));
}
let null_count = self.null_count();
let length = self.len();
if null_count == length {
return Ok(None);
}
let (idx, float_idx, top_idx) = quantile_idx(quantile, length, null_count, interpol);
let opt = match interpol {
QuantileInterpolOptions::Midpoint => {
if top_idx == idx {
ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.next()
.flatten()
} else {
let bounds: Vec<Option<f64>> = ChunkSort::sort(self, false)
.slice(idx, 2)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.collect();
Some((bounds[0].unwrap() + bounds[1].unwrap()) / 2.0f64)
}
}
QuantileInterpolOptions::Linear => {
if top_idx == idx {
ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.next()
.flatten()
} else {
let bounds: Vec<Option<f64>> = ChunkSort::sort(self, false)
.slice(idx, 2)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.collect();
linear_interpol(&bounds, idx, float_idx)
}
}
_ => ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.next()
.flatten(),
};
Ok(opt)
}
fn median(&self) -> Option<f64> {
self.quantile(0.5, QuantileInterpolOptions::Linear).unwrap() // unwrap fine since quantile in range
}
}
impl ChunkQuantile<f32> for Float32Chunked {
fn quantile(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Option<f32>> {
if !(0.0..=1.0).contains(&quantile) {
return Err(PolarsError::ComputeError(
"quantile should be between 0.0 and 1.0".into(),
));
}
let null_count = self.null_count();
let length = self.len();
if null_count == length {
return Ok(None);
}
let (idx, float_idx, top_idx) = quantile_idx(quantile, length, null_count, interpol);
let opt = match interpol {
QuantileInterpolOptions::Midpoint => {
if top_idx == idx {
ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float32Type>(|value| value.to_f32().unwrap())
.into_iter()
.next()
.flatten()
} else {
let bounds: Vec<Option<f32>> = ChunkSort::sort(self, false)
.slice(idx, 2)
.apply_cast_numeric::<_, Float32Type>(|value| value.to_f32().unwrap())
.into_iter()
.collect();
Some((bounds[0].unwrap() + bounds[1].unwrap()) / 2.0f32)
}
}
QuantileInterpolOptions::Linear => {
if top_idx == idx {
ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float32Type>(|value| value.to_f32().unwrap())
.into_iter()
.next()
.flatten()
} else {
let bounds: Vec<Option<f32>> = ChunkSort::sort(self, false)
.slice(idx, 2)
.apply_cast_numeric::<_, Float32Type>(|value| value.to_f32().unwrap())
.into_iter()
.collect();
linear_interpol(&bounds, idx, float_idx)
}
}
_ => ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float32Type>(|value| value.to_f32().unwrap())
.into_iter()
.next()
.flatten(),
};
Ok(opt)
}
fn median(&self) -> Option<f32> {
self.quantile(0.5, QuantileInterpolOptions::Linear).unwrap() // unwrap fine since quantile in range
}
}
impl ChunkQuantile<f64> for Float64Chunked {
fn quantile(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Option<f64>> {
if !(0.0..=1.0).contains(&quantile) {
return Err(PolarsError::ComputeError(
"quantile should be between 0.0 and 1.0".into(),
));
}
let null_count = self.null_count();
let length = self.len();
if null_count == length {
return Ok(None);
}
let (idx, float_idx, top_idx) = quantile_idx(quantile, length, null_count, interpol);
let opt = match interpol {
QuantileInterpolOptions::Midpoint => {
if top_idx == idx {
ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.next()
.flatten()
} else {
let bounds: Vec<Option<f64>> = ChunkSort::sort(self, false)
.slice(idx, 2)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.collect();
Some((bounds[0].unwrap() + bounds[1].unwrap()) / 2.0f64)
}
}
QuantileInterpolOptions::Linear => {
if top_idx == idx {
ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.next()
.flatten()
} else {
let bounds: Vec<Option<f64>> = ChunkSort::sort(self, false)
.slice(idx, 2)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.collect();
linear_interpol(&bounds, idx, float_idx)
}
}
_ => ChunkSort::sort(self, false)
.slice(idx, 1)
.apply_cast_numeric::<_, Float64Type>(|value| value.to_f64().unwrap())
.into_iter()
.next()
.flatten(),
};
Ok(opt)
}
fn median(&self) -> Option<f64> {
self.quantile(0.5, QuantileInterpolOptions::Linear).unwrap() // unwrap fine since quantile in range
}
}
impl ChunkQuantile<String> for Utf8Chunked {}
impl ChunkQuantile<Series> for ListChunked {}
#[cfg(feature = "object")]
impl<T: PolarsObject> ChunkQuantile<Series> for ObjectChunked<T> {}
impl ChunkQuantile<bool> for BooleanChunked {}
impl<T> ChunkVar<f64> for ChunkedArray<T>
where
T: PolarsIntegerType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn var(&self, ddof: u8) -> Option<f64> {
if self.len() == 1 {
return Some(0.0);
}
let n_values = self.len() - self.null_count();
if ddof as usize > n_values {
return None;
}
let n_values = n_values as f64;
let mean = self.mean()?;
let squared = self.apply_cast_numeric::<_, Float64Type>(|value| {
let tmp = value.to_f64().unwrap() - mean;
tmp * tmp
});
// Note, this is similar behavior to numpy if DDOF=1.
// in statistics DDOF often = 1.
// this last step is similar to mean, only now instead of 1/n it is 1/(n-1)
squared.sum().map(|sum| sum / (n_values - ddof as f64))
}
fn std(&self, ddof: u8) -> Option<f64> {
self.var(ddof).map(|var| var.sqrt())
}
}
impl ChunkVar<f32> for Float32Chunked {
fn var(&self, ddof: u8) -> Option<f32> {
if self.len() == 1 {
return Some(0.0);
}
let n_values = self.len() - self.null_count();
if ddof as usize > n_values {
return None;
}
let n_values = n_values as f32;
let mean = self.mean()? as f32;
let squared = self.apply(|value| {
let tmp = value - mean;
tmp * tmp
});
squared.sum().map(|sum| sum / (n_values - ddof as f32))
}
fn std(&self, ddof: u8) -> Option<f32> {
self.var(ddof).map(|var| var.sqrt())
}
}
impl ChunkVar<f64> for Float64Chunked {
fn var(&self, ddof: u8) -> Option<f64> {
if self.len() == 1 {
return Some(0.0);
}
let n_values = self.len() - self.null_count();
if ddof as usize > n_values {
return None;
}
let n_values = n_values as f64;
let mean = self.mean()?;
let squared = self.apply(|value| {
let tmp = value - mean;
tmp * tmp
});
squared.sum().map(|sum| sum / (n_values - ddof as f64))
}
fn std(&self, ddof: u8) -> Option<f64> {
self.var(ddof).map(|var| var.sqrt())
}
}
impl ChunkVar<String> for Utf8Chunked {}
impl ChunkVar<Series> for ListChunked {}
#[cfg(feature = "object")]
impl<T: PolarsObject> ChunkVar<Series> for ObjectChunked<T> {}
impl ChunkVar<bool> for BooleanChunked {}
/// Booleans are casted to 1 or 0.
impl ChunkAgg<IdxSize> for BooleanChunked {
/// Returns `None` if the array is empty or only contains null values.
fn sum(&self) -> Option<IdxSize> {
if self.is_empty() {
None
} else {
Some(
self.downcast_iter()
.map(|arr| match arr.validity() {
Some(validity) => {
(arr.len() - (validity & arr.values()).unset_bits()) as IdxSize
}
None => (arr.len() - arr.values().unset_bits()) as IdxSize,
})
.sum(),
)
}
}
fn min(&self) -> Option<IdxSize> {
if self.is_empty() {
return None;
}
if self.all() {
Some(1)
} else {
Some(0)
}
}
fn max(&self) -> Option<IdxSize> {
if self.is_empty() {
return None;
}
if self.any() {
Some(1)
} else {
Some(0)
}
}
fn mean(&self) -> Option<f64> {
self.sum()
.map(|sum| sum as f64 / (self.len() - self.null_count()) as f64)
}
}
// Needs the same trait bounds as the implementation of ChunkedArray<T> of dyn Series
impl<T> ChunkAggSeries for ChunkedArray<T>
where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
ChunkedArray<T>: IntoSeries,
{
fn sum_as_series(&self) -> Series {
let v = self.sum();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = self.max();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = self.min();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn prod_as_series(&self) -> Series {
let mut prod = None;
for opt_v in self.into_iter() {
match (prod, opt_v) {
(_, None) => return Self::full_null(self.name(), 1).into_series(),
(None, Some(v)) => prod = Some(v),
(Some(p), Some(v)) => prod = Some(p * v),
}
}
Self::from_slice_options(self.name(), &[prod]).into_series()
}
}
macro_rules! impl_as_series {
($self:expr, $agg:ident, $ty: ty) => {{
let v = $self.$agg();
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
($self:expr, $agg:ident, $arg:expr, $ty: ty) => {{
let v = $self.$agg($arg);
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
}
impl<T> VarAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
impl VarAggSeries for Float32Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float32Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float32Chunked)
}
}
impl VarAggSeries for Float64Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
macro_rules! impl_quantile_as_series {
($self:expr, $agg:ident, $ty: ty, $qtl:expr, $opt:expr) => {{
let v = $self.$agg($qtl, $opt)?;
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
Ok(ca.into_series())
}};
}
impl<T> QuantileAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl QuantileAggSeries for Float32Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float32Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float32Chunked)
}
}
impl QuantileAggSeries for Float64Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl ChunkAggSeries for BooleanChunked {
fn sum_as_series(&self) -> Series {
let v = ChunkAgg::sum(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = ChunkAgg::max(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = ChunkAgg::min(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
}
impl Utf8Chunked {
pub(crate) fn max_str(&self) -> Option<&str> {
match self.is_sorted2() {
IsSorted::Ascending => self.get(self.len() - 1),
IsSorted::Descending => self.get(0),
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::max_string)
.fold_first_(|acc, v| if acc > v { acc } else { v }),
}
}
pub(crate) fn min_str(&self) -> Option<&str> {
match self.is_sorted2() {
IsSorted::Ascending => self.get(0),
IsSorted::Descending => self.get(self.len() - 1),
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::min_string)
.fold_first_(|acc, v| if acc < v { acc } else { v }),
}
}
}
impl ChunkAggSeries for Utf8Chunked {
fn sum_as_series(&self) -> Series {
Utf8Chunked::full_null(self.name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
Series::new(self.name(), &[self.max_str()])
}
fn min_as_series(&self) -> Series {
Series::new(self.name(), &[self.min_str()])
}
}
#[cfg(feature = "dtype-binary")]
impl ChunkAggSeries for BinaryChunked {
fn sum_as_series(&self) -> Series {
BinaryChunked::full_null(self.name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
Series::new(
self.name(),
&[self
.downcast_iter()
.filter_map(compute::aggregate::max_binary)
.fold_first_(|acc, v| if acc > v { acc } else { v })],
)
}
fn min_as_series(&self) -> Series {
Series::new(
self.name(),
&[self
.downcast_iter()
.filter_map(compute::aggregate::min_binary)
.fold_first_(|acc, v| if acc < v { acc } else { v })],
)
}
}
impl ChunkAggSeries for ListChunked {
fn sum_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
fn max_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
fn min_as_series(&self) -> Series {
ListChunked::full_null_with_dtype(self.name(), 1, &self.inner_dtype()).into_series()
}
}
#[cfg(feature = "object")]
impl<T: PolarsObject> ChunkAggSeries for ObjectChunked<T> {}
impl<T> ArgAgg for ChunkedArray<T>
where
T: PolarsNumericType,
{
fn arg_min(&self) -> Option<usize> {
match self.is_sorted2() {
IsSorted::Ascending => Some(0),
IsSorted::Descending => Some(self.len()),
IsSorted::Not => self
.into_iter()
.enumerate()
.reduce(|acc, (idx, val)| if acc.1 > val { (idx, val) } else { acc })
.map(|tpl| tpl.0),
}
}
fn arg_max(&self) -> Option<usize> {
match self.is_sorted2() {
IsSorted::Ascending => Some(self.len()),
IsSorted::Descending => Some(0),
IsSorted::Not => self
.into_iter()
.enumerate()
.reduce(|acc, (idx, val)| if acc.1 < val { (idx, val) } else { acc })
.map(|tpl| tpl.0),
}
}
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
fn cast_impl(&self, data_type: &DataType, checked: bool) -> PolarsResult<Series> {
match data_type {
#[cfg(feature = "dtype-categorical")]
DataType::Categorical(_) => {
Ok(CategoricalChunked::full_null(self.name(), self.len()).into_series())
}
#[cfg(feature = "dtype-struct")]
DataType::Struct(fields) => {
// cast to first field dtype
let fld = &fields[0];
let dtype = &fld.dtype;
let name = &fld.name;
let s = cast_impl_inner(name, &self.chunks, dtype, true)?;
Ok(StructChunked::new_unchecked(self.name(), &[s]).into_series())
}
_ => cast_impl_inner(self.name(), &self.chunks, data_type, checked).map(|mut s| {
// maintain sorted if data types remain signed
// this may still fail with overflow?
if ((self.dtype().is_signed() && data_type.is_signed())
|| (self.dtype().is_unsigned() && data_type.is_unsigned()))
&& (s.null_count() == self.null_count())
{
let is_sorted = self.is_sorted2();
s.set_sorted(is_sorted)
}
s
}),
}
}
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
pub(crate) unsafe fn agg_min(&self, groups: &GroupsProxy) -> Series {
// faster paths
match (self.is_sorted2(), self.null_count()) {
(IsSorted::Ascending, 0) => {
return self.clone().into_series().agg_first(groups);
}
(IsSorted::Descending, 0) => {
return self.clone().into_series().agg_last(groups);
}
_ => {}
}
match groups {
GroupsProxy::Idx(groups) => _agg_helper_idx_bool(groups, |(first, idx)| {
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
None
} else if idx.len() == 1 {
self.get(first as usize)
} else {
// TODO! optimize this
// can just check if any is false and early stop
let take = { self.take_unchecked(idx.into()) };
take.min().map(|v| v == 1)
}
}),
GroupsProxy::Slice {
groups: groups_slice,
..
} => _agg_helper_slice_bool(groups_slice, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.min().map(|v| v == 1)
}
}
}),
}
}
pub(crate) unsafe fn agg_max(&self, groups: &GroupsProxy) -> Series {
// faster paths
match (self.is_sorted2(), self.null_count()) {
(IsSorted::Ascending, 0) => {
return self.clone().into_series().agg_last(groups);
}
(IsSorted::Descending, 0) => {
return self.clone().into_series().agg_first(groups);
}
_ => {}
}
match groups {
GroupsProxy::Idx(groups) => _agg_helper_idx_bool(groups, |(first, idx)| {
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
None
} else if idx.len() == 1 {
self.get(first as usize)
} else {
// TODO! optimize this
// can just check if any is true and early stop
let take = { self.take_unchecked(idx.into()) };
take.max().map(|v| v == 1)
}
}),
GroupsProxy::Slice {
groups: groups_slice,
..
} => _agg_helper_slice_bool(groups_slice, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.max().map(|v| v == 1)
}
}
}),
}
}
pub(crate) unsafe fn agg_sum(&self, groups: &GroupsProxy) -> Series {
self.cast(&IDX_DTYPE).unwrap().agg_sum(groups)
}
}
impl Utf8Chunked {
#[allow(clippy::needless_lifetimes)]
pub(crate) unsafe fn agg_min<'a>(&'a self, groups: &GroupsProxy) -> Series {
// faster paths
match (&self.is_sorted2(), &self.null_count()) {
(IsSorted::Ascending, 0) => {
return self.clone().into_series().agg_first(groups);
}
(IsSorted::Descending, 0) => {
return self.clone().into_series().agg_last(groups);
}
_ => {}
}
match groups {
GroupsProxy::Idx(groups) => {
let ca_self = self.rechunk();
let arr = ca_self.downcast_iter().next().unwrap();
_agg_helper_idx_utf8(groups, |(first, idx)| {
debug_assert!(idx.len() <= ca_self.len());
if idx.is_empty() {
None
} else if idx.len() == 1 {
ca_self.get(first as usize)
} else if self.null_count() == 0 {
take_agg_utf8_iter_unchecked_no_null(
arr,
indexes_to_usizes(idx),
|acc, v| if acc < v { acc } else { v },
)
} else {
take_agg_utf8_iter_unchecked(
arr,
indexes_to_usizes(idx),
|acc, v| if acc < v { acc } else { v },
idx.len() as IdxSize,
)
}
})
}
GroupsProxy::Slice {
groups: groups_slice,
..
} => _agg_helper_slice_utf8(groups_slice, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
let borrowed = arr_group.min_str();
// Safety:
// The borrowed has `arr_group`s lifetime, but it actually points to data
// hold by self. Here we tell the compiler that.
unsafe { std::mem::transmute::<Option<&str>, Option<&'a str>>(borrowed) }
}
}
}),
}
}
#[allow(clippy::needless_lifetimes)]
pub(crate) unsafe fn agg_max<'a>(&'a self, groups: &GroupsProxy) -> Series {
// faster paths
match (self.is_sorted2(), self.null_count()) {
(IsSorted::Ascending, 0) => {
return self.clone().into_series().agg_last(groups);
}
(IsSorted::Descending, 0) => {
return self.clone().into_series().agg_first(groups);
}
_ => {}
}
match groups {
GroupsProxy::Idx(groups) => {
let ca_self = self.rechunk();
let arr = ca_self.downcast_iter().next().unwrap();
_agg_helper_idx_utf8(groups, |(first, idx)| {
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
None
} else if idx.len() == 1 {
ca_self.get(first as usize)
} else if ca_self.null_count() == 0 {
take_agg_utf8_iter_unchecked_no_null(
arr,
indexes_to_usizes(idx),
|acc, v| if acc > v { acc } else { v },
)
} else {
take_agg_utf8_iter_unchecked(
arr,
indexes_to_usizes(idx),
|acc, v| if acc > v { acc } else { v },
idx.len() as IdxSize,
)
}
})
}
GroupsProxy::Slice {
groups: groups_slice,
..
} => _agg_helper_slice_utf8(groups_slice, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
let borrowed = arr_group.max_str();
// Safety:
// The borrowed has `arr_group`s lifetime, but it actually points to data
// hold by self. Here we tell the compiler that.
unsafe { std::mem::transmute::<Option<&str>, Option<&'a str>>(borrowed) }
}
}
}),
}
}
}
#[inline(always)]
fn take_min<T: PartialOrd>(a: T, b: T) -> T {
if a < b {
a
} else {
b
}
}
#[inline(always)]
fn take_max<T: PartialOrd>(a: T, b: T) -> T {
if a > b {
a
} else {
b
}
}
impl<T> ChunkedArray<T>
where
T: PolarsNumericType + Sync,
T::Native:
NativeType + PartialOrd + Num + NumCast + Zero + Simd + Bounded + std::iter::Sum<T::Native>,
<T::Native as Simd>::Simd: std::ops::Add<Output = <T::Native as Simd>::Simd>
+ arrow::compute::aggregate::Sum<T::Native>
+ arrow::compute::aggregate::SimdOrd<T::Native>,
ChunkedArray<T>: IntoSeries,
{
pub(crate) unsafe fn agg_min(&self, groups: &GroupsProxy) -> Series {
// faster paths
match (self.is_sorted2(), self.null_count()) {
(IsSorted::Ascending, 0) => {
return self.clone().into_series().agg_first(groups);
}
(IsSorted::Descending, 0) => {
return self.clone().into_series().agg_last(groups);
}
_ => {}
}
match groups {
GroupsProxy::Idx(groups) => _agg_helper_idx::<T, _>(groups, |(first, idx)| {
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
None
} else if idx.len() == 1 {
self.get(first as usize)
} else {
match (self.has_validity(), self.chunks.len()) {
(false, 1) => Some(take_agg_no_null_primitive_iter_unchecked(
self.downcast_iter().next().unwrap(),
idx.iter().map(|i| *i as usize),
take_min,
T::Native::max_value(),
)),
(_, 1) => take_agg_primitive_iter_unchecked::<T::Native, _, _>(
self.downcast_iter().next().unwrap(),
idx.iter().map(|i| *i as usize),
take_min,
T::Native::max_value(),
idx.len() as IdxSize,
),
_ => {
let take = { self.take_unchecked(idx.into()) };
take.min()
}
}
}
}),
GroupsProxy::Slice {
groups: groups_slice,
..
} => {
if _use_rolling_kernels(groups_slice, self.chunks()) {
let arr = self.downcast_iter().next().unwrap();
let values = arr.values().as_slice();
let offset_iter = groups_slice.iter().map(|[first, len]| (*first, *len));
let arr = match arr.validity() {
None => _rolling_apply_agg_window_no_nulls::<MinWindow<_>, _, _>(
values,
offset_iter,
),
Some(validity) => _rolling_apply_agg_window_nulls::<
rolling::nulls::MinWindow<_>,
_,
_,
>(values, validity, offset_iter),
};
Self::from_chunks("", vec![arr]).into_series()
} else {
_agg_helper_slice::<T, _>(groups_slice, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.min()
}
}
})
}
}
}
}
pub(crate) unsafe fn agg_max(&self, groups: &GroupsProxy) -> Series {
// faster paths
match (self.is_sorted2(), self.null_count()) {
(IsSorted::Ascending, 0) => {
return self.clone().into_series().agg_last(groups);
}
(IsSorted::Descending, 0) => {
return self.clone().into_series().agg_first(groups);
}
_ => {}
}
match groups {
GroupsProxy::Idx(groups) => _agg_helper_idx::<T, _>(groups, |(first, idx)| {
debug_assert!(idx.len() <= self.len());
if idx.is_empty() {
None
} else if idx.len() == 1 {
self.get(first as usize)
} else {
match (self.has_validity(), self.chunks.len()) {
(false, 1) => Some({
take_agg_no_null_primitive_iter_unchecked(
self.downcast_iter().next().unwrap(),
idx.iter().map(|i| *i as usize),
take_max,
T::Native::min_value(),
)
}),
(_, 1) => take_agg_primitive_iter_unchecked::<T::Native, _, _>(
self.downcast_iter().next().unwrap(),
idx.iter().map(|i| *i as usize),
take_max,
T::Native::min_value(),
idx.len() as IdxSize,
),
_ => {
let take = { self.take_unchecked(idx.into()) };
take.max()
}
}
}
}),
GroupsProxy::Slice {
groups: groups_slice,
..
} => {
if _use_rolling_kernels(groups_slice, self.chunks()) {
let arr = self.downcast_iter().next().unwrap();
let values = arr.values().as_slice();
let offset_iter = groups_slice.iter().map(|[first, len]| (*first, *len));
let arr = match arr.validity() {
None => _rolling_apply_agg_window_no_nulls::<MaxWindow<_>, _, _>(
values,
offset_iter,
),
Some(validity) => _rolling_apply_agg_window_nulls::<
rolling::nulls::MaxWindow<_>,
_,
_,
>(values, validity, offset_iter),
};
Self::from_chunks("", vec![arr]).into_series()
} else {
_agg_helper_slice::<T, _>(groups_slice, |[first, len]| {
debug_assert!(len <= self.len() as IdxSize);
match len {
0 => None,
1 => self.get(first as usize),
_ => {
let arr_group = _slice_from_offsets(self, first, len);
arr_group.max()
}
}
})
}
}
}
}
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
fn unique(&self) -> PolarsResult<Self> {
// prevent stackoverflow repeated sorted.unique call
if self.is_empty() {
return Ok(self.clone());
}
match self.is_sorted2() {
IsSorted::Ascending | IsSorted::Descending => {
// TODO! optimize this branch
if self.null_count() > 0 {
let mut arr = MutablePrimitiveArray::with_capacity(self.len());
let mut iter = self.into_iter();
let mut last = None;
if let Some(val) = iter.next() {
last = val;
arr.push(val)
};
#[allow(clippy::unnecessary_filter_map)]
let to_extend = iter.filter_map(|opt_val| {
if opt_val != last {
last = opt_val;
Some(opt_val)
} else {
None
}
});
arr.extend(to_extend);
let arr: PrimitiveArray<T::Native> = arr.into();
Ok(ChunkedArray::from_chunks(
self.name(),
vec![Box::new(arr) as ArrayRef],
))
} else {
let mask = self.not_equal(&self.shift(1));
self.filter(&mask)
}
}
IsSorted::Not => {
let sorted = self.sort(false);
sorted.unique()
}
}
}
sourcepub fn set_sorted2(&mut self, sorted: IsSorted)
pub fn set_sorted2(&mut self, sorted: IsSorted)
Examples found in repository?
More examples
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
fn _set_sorted(&mut self, is_sorted: IsSorted) {
self.0.set_sorted2(is_sorted)
}
unsafe fn equal_element(&self, idx_self: usize, idx_other: usize, other: &Series) -> bool {
self.0.equal_element(idx_self, idx_other, other)
}
#[cfg(feature = "zip_with")]
fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
ChunkZip::zip_with(&self.0, mask, other.as_ref().as_ref()).map(|ca| ca.into_series())
}
fn into_partial_eq_inner<'a>(&'a self) -> Box<dyn PartialEqInner + 'a> {
(&self.0).into_partial_eq_inner()
}
fn into_partial_ord_inner<'a>(&'a self) -> Box<dyn PartialOrdInner + 'a> {
(&self.0).into_partial_ord_inner()
}
fn vec_hash(&self, random_state: RandomState, buf: &mut Vec<u64>) -> PolarsResult<()> {
self.0.vec_hash(random_state, buf);
Ok(())
}
fn vec_hash_combine(&self, build_hasher: RandomState, hashes: &mut [u64]) -> PolarsResult<()> {
self.0.vec_hash_combine(build_hasher, hashes);
Ok(())
}
unsafe fn agg_list(&self, groups: &GroupsProxy) -> Series {
self.0.agg_list(groups)
}
unsafe fn agg_min(&self, groups: &GroupsProxy) -> Series {
self.0.agg_min(groups)
}
unsafe fn agg_max(&self, groups: &GroupsProxy) -> Series {
self.0.agg_max(groups)
}
fn zip_outer_join_column(
&self,
right_column: &Series,
opt_join_tuples: &[(Option<IdxSize>, Option<IdxSize>)],
) -> Series {
ZipOuterJoinColumn::zip_outer_join_column(&self.0, right_column, opt_join_tuples)
}
fn subtract(&self, rhs: &Series) -> PolarsResult<Series> {
NumOpsDispatch::subtract(&self.0, rhs)
}
fn add_to(&self, rhs: &Series) -> PolarsResult<Series> {
NumOpsDispatch::add_to(&self.0, rhs)
}
fn multiply(&self, rhs: &Series) -> PolarsResult<Series> {
NumOpsDispatch::multiply(&self.0, rhs)
}
fn divide(&self, rhs: &Series) -> PolarsResult<Series> {
NumOpsDispatch::divide(&self.0, rhs)
}
fn remainder(&self, rhs: &Series) -> PolarsResult<Series> {
NumOpsDispatch::remainder(&self.0, rhs)
}
fn group_tuples(&self, multithreaded: bool, sorted: bool) -> PolarsResult<GroupsProxy> {
IntoGroupsProxy::group_tuples(&self.0, multithreaded, sorted)
}
#[cfg(feature = "sort_multiple")]
fn argsort_multiple(&self, by: &[Series], reverse: &[bool]) -> PolarsResult<IdxCa> {
self.0.argsort_multiple(by, reverse)
}
}
impl SeriesTrait for SeriesWrap<Utf8Chunked> {
fn is_sorted(&self) -> IsSorted {
if self.0.is_sorted() {
IsSorted::Ascending
} else if self.0.is_sorted_reverse() {
IsSorted::Descending
} else {
IsSorted::Not
}
}
fn rename(&mut self, name: &str) {
self.0.rename(name);
}
fn chunk_lengths(&self) -> ChunkIdIter {
self.0.chunk_id()
}
fn name(&self) -> &str {
self.0.name()
}
fn chunks(&self) -> &Vec<ArrayRef> {
self.0.chunks()
}
fn shrink_to_fit(&mut self) {
self.0.shrink_to_fit()
}
fn slice(&self, offset: i64, length: usize) -> Series {
self.0.slice(offset, length).into_series()
}
fn append(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
// todo! add object
self.0.append(other.as_ref().as_ref());
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot append Series; data types don't match".into(),
))
}
}
fn extend(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
self.0.extend(other.as_ref().as_ref());
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot extend Series; data types don't match".into(),
))
}
}
fn filter(&self, filter: &BooleanChunked) -> PolarsResult<Series> {
ChunkFilter::filter(&self.0, filter).map(|ca| ca.into_series())
}
#[cfg(feature = "chunked_ids")]
unsafe fn _take_chunked_unchecked(&self, by: &[ChunkId], sorted: IsSorted) -> Series {
self.0.take_chunked_unchecked(by, sorted).into_series()
}
#[cfg(feature = "chunked_ids")]
unsafe fn _take_opt_chunked_unchecked(&self, by: &[Option<ChunkId>]) -> Series {
self.0.take_opt_chunked_unchecked(by).into_series()
}
fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
let indices = if indices.chunks.len() > 1 {
Cow::Owned(indices.rechunk())
} else {
Cow::Borrowed(indices)
};
Ok(ChunkTake::take(&self.0, (&*indices).into())?.into_series())
}
fn take_iter(&self, iter: &mut dyn TakeIterator) -> PolarsResult<Series> {
Ok(ChunkTake::take(&self.0, iter.into())?.into_series())
}
fn take_every(&self, n: usize) -> Series {
self.0.take_every(n).into_series()
}
unsafe fn take_iter_unchecked(&self, iter: &mut dyn TakeIterator) -> Series {
ChunkTake::take_unchecked(&self.0, iter.into()).into_series()
}
unsafe fn take_unchecked(&self, idx: &IdxCa) -> PolarsResult<Series> {
let idx = if idx.chunks.len() > 1 {
Cow::Owned(idx.rechunk())
} else {
Cow::Borrowed(idx)
};
let mut out = ChunkTake::take_unchecked(&self.0, (&*idx).into());
if self.0.is_sorted() && (idx.is_sorted() || idx.is_sorted_reverse()) {
out.set_sorted2(idx.is_sorted2())
}
Ok(out.into_series())
}
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
pub fn append(&mut self, other: &Self) {
let len = self.len();
self.length += other.length;
new_chunks(&mut self.chunks, &other.chunks, len);
self.set_sorted2(IsSorted::Not);
}
}
#[doc(hidden)]
impl BooleanChunked {
pub fn append(&mut self, other: &Self) {
let len = self.len();
self.length += other.length;
new_chunks(&mut self.chunks, &other.chunks, len);
self.set_sorted2(IsSorted::Not);
}
}
#[doc(hidden)]
impl Utf8Chunked {
pub fn append(&mut self, other: &Self) {
let len = self.len();
self.length += other.length;
new_chunks(&mut self.chunks, &other.chunks, len);
self.set_sorted2(IsSorted::Not);
}
}
#[cfg(feature = "dtype-binary")]
#[doc(hidden)]
impl BinaryChunked {
pub fn append(&mut self, other: &Self) {
let len = self.len();
self.length += other.length;
new_chunks(&mut self.chunks, &other.chunks, len);
self.set_sorted2(IsSorted::Not);
}
}
#[doc(hidden)]
impl ListChunked {
pub fn append(&mut self, other: &Self) -> PolarsResult<()> {
let dtype = merge_dtypes(self.dtype(), other.dtype())?;
self.field = Arc::new(Field::new(self.name(), dtype));
let len = self.len();
self.length += other.length;
new_chunks(&mut self.chunks, &other.chunks, len);
self.set_sorted2(IsSorted::Not);
if !other._can_fast_explode() {
self.unset_fast_explode()
}
Ok(())
}
}
#[cfg(feature = "object")]
#[doc(hidden)]
impl<T: PolarsObject> ObjectChunked<T> {
pub fn append(&mut self, other: &Self) {
let len = self.len();
self.length += other.length;
self.set_sorted2(IsSorted::Not);
new_chunks(&mut self.chunks, &other.chunks, len);
}
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
fn full(name: &str, value: T::Native, length: usize) -> Self {
let data = vec![value; length];
let mut out = ChunkedArray::from_vec(name, data);
out.set_sorted2(IsSorted::Ascending);
out
}
}
impl<T> ChunkFullNull for ChunkedArray<T>
where
T: PolarsNumericType,
{
fn full_null(name: &str, length: usize) -> Self {
let arr = new_null_array(T::get_dtype().to_arrow(), length);
ChunkedArray::from_chunks(name, vec![arr])
}
}
impl ChunkFull<bool> for BooleanChunked {
fn full(name: &str, value: bool, length: usize) -> Self {
let mut bits = MutableBitmap::with_capacity(length);
bits.extend_constant(length, value);
let mut out: BooleanChunked =
(name, BooleanArray::from_data_default(bits.into(), None)).into();
out.set_sorted2(IsSorted::Ascending);
out
}
}
impl ChunkFullNull for BooleanChunked {
fn full_null(name: &str, length: usize) -> Self {
let arr = new_null_array(DataType::Boolean.to_arrow(), length);
BooleanChunked::from_chunks(name, vec![arr])
}
}
impl<'a> ChunkFull<&'a str> for Utf8Chunked {
fn full(name: &str, value: &'a str, length: usize) -> Self {
let mut builder = Utf8ChunkedBuilder::new(name, length, length * value.len());
for _ in 0..length {
builder.append_value(value);
}
let mut out = builder.finish();
out.set_sorted2(IsSorted::Ascending);
out
}
sourcepub fn first_non_null(&self) -> Option<usize>
pub fn first_non_null(&self) -> Option<usize>
Get the index of the first non null value in this ChunkedArray.
Examples found in repository?
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
fn min(&self) -> Option<T::Native> {
match self.is_sorted2() {
IsSorted::Ascending => {
self.first_non_null().and_then(|idx| {
// Safety:
// first_non_null returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Descending => {
self.last_non_null().and_then(|idx| {
// Safety:
// last returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::min_primitive)
.fold_first_(|acc, v| {
if matches!(compare_fn_nan_max(&acc, &v), Ordering::Less) {
acc
} else {
v
}
}),
}
}
fn max(&self) -> Option<T::Native> {
match self.is_sorted2() {
IsSorted::Ascending => {
self.last_non_null().and_then(|idx| {
// Safety:
// first_non_null returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Descending => {
self.first_non_null().and_then(|idx| {
// Safety:
// last returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::max_primitive)
.fold_first_(|acc, v| {
if matches!(compare_fn_nan_min(&acc, &v), Ordering::Greater) {
acc
} else {
v
}
}),
}
}
sourcepub fn last_non_null(&self) -> Option<usize>
pub fn last_non_null(&self) -> Option<usize>
Get the index of the last non null value in this ChunkedArray.
Examples found in repository?
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
fn min(&self) -> Option<T::Native> {
match self.is_sorted2() {
IsSorted::Ascending => {
self.first_non_null().and_then(|idx| {
// Safety:
// first_non_null returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Descending => {
self.last_non_null().and_then(|idx| {
// Safety:
// last returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::min_primitive)
.fold_first_(|acc, v| {
if matches!(compare_fn_nan_max(&acc, &v), Ordering::Less) {
acc
} else {
v
}
}),
}
}
fn max(&self) -> Option<T::Native> {
match self.is_sorted2() {
IsSorted::Ascending => {
self.last_non_null().and_then(|idx| {
// Safety:
// first_non_null returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Descending => {
self.first_non_null().and_then(|idx| {
// Safety:
// last returns in bound index
unsafe { self.get_unchecked(idx) }
})
}
IsSorted::Not => self
.downcast_iter()
.filter_map(compute::aggregate::max_primitive)
.fold_first_(|acc, v| {
if matches!(compare_fn_nan_min(&acc, &v), Ordering::Greater) {
acc
} else {
v
}
}),
}
}
sourcepub fn iter_validities(
&self
) -> Map<Iter<'_, ArrayRef>, fn(_: &ArrayRef) -> Option<&Bitmap>>
pub fn iter_validities(
&self
) -> Map<Iter<'_, ArrayRef>, fn(_: &ArrayRef) -> Option<&Bitmap>>
Get the buffer of bits representing null values
Examples found in repository?
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
pub fn first_non_null(&self) -> Option<usize> {
if self.is_empty() {
None
} else {
first_non_null(self.iter_validities())
}
}
/// Get the index of the last non null value in this ChunkedArray.
pub fn last_non_null(&self) -> Option<usize> {
last_non_null(self.iter_validities(), self.length as usize)
}
/// Get the buffer of bits representing null values
#[inline]
#[allow(clippy::type_complexity)]
pub fn iter_validities(&self) -> Map<Iter<'_, ArrayRef>, fn(&ArrayRef) -> Option<&Bitmap>> {
fn to_validity(arr: &ArrayRef) -> Option<&Bitmap> {
arr.validity()
}
self.chunks.iter().map(to_validity)
}
#[inline]
/// Return if any the chunks in this `[ChunkedArray]` have a validity bitmap.
/// no bitmap means no null values.
pub fn has_validity(&self) -> bool {
self.iter_validities().any(|valid| valid.is_some())
}
More examples
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
fn apply_cast_numeric<F, S>(&self, f: F) -> ChunkedArray<S>
where
F: Fn(T::Native) -> S::Native + Copy,
S: PolarsNumericType,
{
let chunks = self
.data_views()
.zip(self.iter_validities())
.map(|(slice, validity)| {
let values = Vec::<_>::from_trusted_len_iter(slice.iter().map(|&v| f(v)));
to_array::<S>(values, validity.cloned())
})
.collect();
ChunkedArray::<S>::from_chunks(self.name(), chunks)
}
fn branch_apply_cast_numeric_no_null<F, S>(&self, f: F) -> ChunkedArray<S>
where
F: Fn(Option<T::Native>) -> S::Native,
S: PolarsNumericType,
{
let chunks = self
.downcast_iter()
.map(|array| {
let values = if !array.has_validity() {
let values = array.values().iter().map(|&v| f(Some(v)));
Vec::<_>::from_trusted_len_iter(values)
} else {
let values = array.into_iter().map(|v| f(v.copied()));
Vec::<_>::from_trusted_len_iter(values)
};
to_array::<S>(values, None)
})
.collect();
ChunkedArray::<S>::from_chunks(self.name(), chunks)
}
fn apply<F>(&'a self, f: F) -> Self
where
F: Fn(T::Native) -> T::Native + Copy,
{
let chunks = self
.data_views()
.into_iter()
.zip(self.iter_validities())
.map(|(slice, validity)| {
let values = slice.iter().copied().map(f);
let values = Vec::<_>::from_trusted_len_iter(values);
to_array::<T>(values, validity.cloned())
})
.collect();
ChunkedArray::<T>::from_chunks(self.name(), chunks)
}
fn try_apply<F>(&'a self, f: F) -> PolarsResult<Self>
where
F: Fn(T::Native) -> PolarsResult<T::Native> + Copy,
{
let mut ca: ChunkedArray<T> = self
.data_views()
.into_iter()
.zip(self.iter_validities())
.map(|(slice, validity)| {
let vec: PolarsResult<Vec<_>> = slice.iter().copied().map(f).collect();
Ok((vec?, validity.cloned()))
})
.collect::<PolarsResult<_>>()?;
ca.rename(self.name());
Ok(ca)
}
sourcepub fn has_validity(&self) -> bool
pub fn has_validity(&self) -> bool
Return if any the chunks in this [ChunkedArray]
have a validity bitmap.
no bitmap means no null values.
Examples found in repository?
More examples
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
pub fn is_optimal_aligned(&self) -> bool {
self.chunks.len() == 1 && !self.has_validity()
}
/// Count the null values.
#[inline]
pub fn null_count(&self) -> usize {
self.chunks.iter().map(|arr| arr.null_count()).sum()
}
/// Create a new ChunkedArray from self, where the chunks are replaced.
fn copy_with_chunks(&self, chunks: Vec<ArrayRef>, keep_sorted: bool) -> Self {
let mut out = ChunkedArray {
field: self.field.clone(),
chunks,
phantom: PhantomData,
bit_settings: self.bit_settings,
length: 0,
};
out.compute_len();
if !keep_sorted {
out.set_sorted2(IsSorted::Not);
}
out
}
/// Get a mask of the null values.
pub fn is_null(&self) -> BooleanChunked {
if !self.has_validity() {
return BooleanChunked::full("is_null", false, self.len());
}
let chunks = self
.chunks
.iter()
.map(|arr| {
let bitmap = arr
.validity()
.map(|bitmap| !bitmap)
.unwrap_or_else(|| Bitmap::new_zeroed(arr.len()));
Box::new(BooleanArray::from_data_default(bitmap, None)) as ArrayRef
})
.collect::<Vec<_>>();
BooleanChunked::from_chunks(self.name(), chunks)
}
/// Get a mask of the valid values.
pub fn is_not_null(&self) -> BooleanChunked {
if !self.has_validity() {
return BooleanChunked::full("is_not_null", true, self.len());
}
let chunks = self
.chunks
.iter()
.map(|arr| {
let bitmap = arr
.validity()
.cloned()
.unwrap_or_else(|| !(&Bitmap::new_zeroed(arr.len())));
Box::new(BooleanArray::from_data_default(bitmap, None)) as ArrayRef
})
.collect::<Vec<_>>();
BooleanChunked::from_chunks(self.name(), chunks)
}
- src/chunked_array/ops/take/take_every.rs
- src/chunked_array/arithmetic.rs
- src/chunked_array/ops/apply.rs
- src/chunked_array/ops/take/take_random.rs
- src/chunked_array/ops/compare_inner.rs
- src/chunked_array/ops/chunkops.rs
- src/chunked_array/logical/categorical/mod.rs
- src/frame/hash_join/single_keys_dispatch.rs
- src/chunked_array/ops/set.rs
- src/frame/groupby/into_groups.rs
- src/chunked_array/ops/fill_null.rs
- src/chunked_array/ops/sort/mod.rs
- src/frame/groupby/aggregations/mod.rs
- src/chunked_array/ops/take/mod.rs
sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrink the capacity of this array to fit its length.
Examples found in repository?
More examples
sourcepub fn unpack_series_matching_type(
&self,
series: &Series
) -> PolarsResult<&ChunkedArray<T>>
pub fn unpack_series_matching_type(
&self,
series: &Series
) -> PolarsResult<&ChunkedArray<T>>
Series to ChunkedArray
Examples found in repository?
119 120 121 122 123 124 125 126 127 128 129 130 131 132
fn bitxor(&self, other: &Series) -> PolarsResult<Series> {
let other = self.0.unpack_series_matching_type(other)?;
Ok((&self.0).bitxor(other).into_series())
}
fn bitand(&self, other: &Series) -> PolarsResult<Series> {
let other = self.0.unpack_series_matching_type(other)?;
Ok((&self.0).bitand(other).into_series())
}
fn bitor(&self, other: &Series) -> PolarsResult<Series> {
let other = self.0.unpack_series_matching_type(other)?;
Ok((&self.0).bitor(other).into_series())
}
More examples
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
fn zip_outer_join_column(
&self,
right_column: &Series,
opt_join_tuples: &[(Option<IdxSize>, Option<IdxSize>)],
) -> Series {
let right_ca = self.unpack_series_matching_type(right_column).unwrap();
let left_rand_access = self.take_rand();
let right_rand_access = right_ca.take_rand();
opt_join_tuples
.iter()
.map(|(opt_left_idx, opt_right_idx)| {
if let Some(left_idx) = opt_left_idx {
unsafe { left_rand_access.get_unchecked(*left_idx as usize) }
} else {
unsafe {
let right_idx = opt_right_idx.unwrap_unchecked();
right_rand_access.get_unchecked(right_idx as usize)
}
}
})
.collect_trusted::<ChunkedArray<T>>()
.into_series()
}
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
unsafe fn is_in_helper<T, P>(ca: &ChunkedArray<T>, other: &Series) -> PolarsResult<BooleanChunked>
where
T: PolarsNumericType,
P: Eq + Hash + Copy,
{
let mut set = HashSet::with_capacity(other.len());
let other = ca.unpack_series_matching_type(other)?;
other.downcast_iter().for_each(|iter| {
iter.into_iter().for_each(|opt_val| {
// Safety
// bit sizes are/ should be equal
let ptr = &opt_val.copied() as *const Option<T::Native> as *const Option<P>;
let opt_val = *ptr;
set.insert(opt_val);
})
});
let name = ca.name();
let mut ca: BooleanChunked = ca
.into_iter()
.map(|opt_val| {
// Safety
// bit sizes are/ should be equal
let ptr = &opt_val as *const Option<T::Native> as *const Option<P>;
let opt_val = *ptr;
set.contains(&opt_val)
})
.collect_trusted();
ca.rename(name);
Ok(ca)
}
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
pub(crate) fn join_asof(
&self,
other: &Series,
strategy: AsofStrategy,
tolerance: Option<AnyValue<'static>>,
) -> PolarsResult<Vec<Option<IdxSize>>> {
let other = self.unpack_series_matching_type(other)?;
// cont_slice requires a single chunk
let ca = self.rechunk();
let other = other.rechunk();
let out = match strategy {
AsofStrategy::Forward => match tolerance {
None => join_asof_forward(ca.cont_slice().unwrap(), other.cont_slice().unwrap()),
Some(tolerance) => {
let tolerance = tolerance.extract::<T::Native>().unwrap();
join_asof_forward_with_tolerance(
ca.cont_slice().unwrap(),
other.cont_slice().unwrap(),
tolerance,
)
}
},
AsofStrategy::Backward => match tolerance {
None => join_asof_backward(ca.cont_slice().unwrap(), other.cont_slice().unwrap()),
Some(tolerance) => {
let tolerance = tolerance.extract::<T::Native>().unwrap();
join_asof_backward_with_tolerance(
self.cont_slice().unwrap(),
other.cont_slice().unwrap(),
tolerance,
)
}
},
};
Ok(out)
}
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
fn rolling_apply(
&self,
f: &dyn Fn(&Series) -> Series,
options: RollingOptionsFixedWindow,
) -> PolarsResult<Series> {
check_input(options.window_size, options.min_periods)?;
let ca = self.rechunk();
if options.weights.is_some()
&& !matches!(self.dtype(), DataType::Float64 | DataType::Float32)
{
let s = self.cast(&DataType::Float64)?;
return s.rolling_apply(f, options);
}
if options.window_size >= self.len() {
return Ok(Self::full_null(self.name(), self.len()).into_series());
}
let len = self.len();
let arr = ca.downcast_iter().next().unwrap();
let mut series_container =
ChunkedArray::<T>::from_slice("", &[T::Native::zero()]).into_series();
let array_ptr = series_container.array_ref(0);
let ptr = array_ptr.as_ref() as *const dyn Array as *mut dyn Array
as *mut PrimitiveArray<T::Native>;
let mut builder = PrimitiveChunkedBuilder::<T>::new(self.name(), self.len());
if let Some(weights) = options.weights {
let weights_series = Float64Chunked::new("weights", &weights).into_series();
let weights_series = weights_series.cast(self.dtype()).unwrap();
for idx in 0..len {
let (start, size) = window_edges(idx, len, options.window_size, options.center);
if size < options.min_periods {
builder.append_null();
} else {
// safety:
// we are in bounds
let arr_window = unsafe { arr.slice_unchecked(start, size) };
// Safety.
// ptr is not dropped as we are in scope
// We are also the only owner of the contents of the Arc
// we do this to reduce heap allocs.
unsafe {
*ptr = arr_window;
}
// ensure the length is correct
series_container._get_inner_mut().compute_len();
let s = if size == options.window_size {
f(&series_container.multiply(&weights_series).unwrap())
} else {
let weights_cutoff: Series = match self.dtype() {
DataType::Float64 => weights_series
.f64()
.unwrap()
.into_iter()
.take(series_container.len())
.collect(),
_ => weights_series // Float32 case
.f32()
.unwrap()
.into_iter()
.take(series_container.len())
.collect(),
};
f(&series_container.multiply(&weights_cutoff).unwrap())
};
let out = self.unpack_series_matching_type(&s)?;
builder.append_option(out.get(0));
}
}
Ok(builder.finish().into_series())
} else {
for idx in 0..len {
let (start, size) = window_edges(idx, len, options.window_size, options.center);
if size < options.min_periods {
builder.append_null();
} else {
// safety:
// we are in bounds
let arr_window = unsafe { arr.slice_unchecked(start, size) };
// Safety.
// ptr is not dropped as we are in scope
// We are also the only owner of the contents of the Arc
// we do this to reduce heap allocs.
unsafe {
*ptr = arr_window;
}
// ensure the length is correct
series_container._get_inner_mut().compute_len();
let s = f(&series_container);
let out = self.unpack_series_matching_type(&s)?;
builder.append_option(out.get(0));
}
}
Ok(builder.finish().into_series())
}
}
sourcepub fn chunk_id(&self) -> ChunkIdIter<'_>
pub fn chunk_id(&self) -> ChunkIdIter<'_>
Unique id representing the number of chunks
Examples found in repository?
More examples
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
fn gt(&self, rhs: &Utf8Chunked) -> BooleanChunked {
// broadcast
if rhs.len() == 1 {
if let Some(value) = rhs.get(0) {
self.gt(value)
} else {
BooleanChunked::full("", false, self.len())
}
} else if self.len() == 1 {
if let Some(value) = self.get(0) {
rhs.lt(value)
} else {
BooleanChunked::full("", false, self.len())
}
}
// same length
else if self.chunk_id().zip(rhs.chunk_id()).all(|(l, r)| l == r) {
self.comparison(rhs, |l, r| comparison::gt(l, r))
} else {
apply_operand_on_chunkedarray_by_iter!(self, rhs, >)
}
}
fn gt_eq(&self, rhs: &Utf8Chunked) -> BooleanChunked {
// broadcast
if rhs.len() == 1 {
if let Some(value) = rhs.get(0) {
self.gt_eq(value)
} else {
BooleanChunked::full("", false, self.len())
}
} else if self.len() == 1 {
if let Some(value) = self.get(0) {
rhs.lt_eq(value)
} else {
BooleanChunked::full("", false, self.len())
}
}
// same length
else if self.chunk_id().zip(rhs.chunk_id()).all(|(l, r)| l == r) {
self.comparison(rhs, |l, r| comparison::gt_eq(l, r))
} else {
apply_operand_on_chunkedarray_by_iter!(self, rhs, >=)
}
}
fn lt(&self, rhs: &Utf8Chunked) -> BooleanChunked {
// broadcast
if rhs.len() == 1 {
if let Some(value) = rhs.get(0) {
self.lt(value)
} else {
BooleanChunked::full("", false, self.len())
}
} else if self.len() == 1 {
if let Some(value) = self.get(0) {
rhs.gt(value)
} else {
BooleanChunked::full("", false, self.len())
}
}
// same length
else if self.chunk_id().zip(rhs.chunk_id()).all(|(l, r)| l == r) {
self.comparison(rhs, |l, r| comparison::lt(l, r))
} else {
apply_operand_on_chunkedarray_by_iter!(self, rhs, <)
}
}
fn lt_eq(&self, rhs: &Utf8Chunked) -> BooleanChunked {
// broadcast
if rhs.len() == 1 {
if let Some(value) = rhs.get(0) {
self.lt_eq(value)
} else {
BooleanChunked::full("", false, self.len())
}
} else if self.len() == 1 {
if let Some(value) = self.get(0) {
rhs.gt_eq(value)
} else {
BooleanChunked::full("", false, self.len())
}
}
// same length
else if self.chunk_id().zip(rhs.chunk_id()).all(|(l, r)| l == r) {
self.comparison(rhs, |l, r| comparison::lt_eq(l, r))
} else {
apply_operand_on_chunkedarray_by_iter!(self, rhs, <=)
}
}
sourcepub fn chunks(&self) -> &Vec<ArrayRef> ⓘ
pub fn chunks(&self) -> &Vec<ArrayRef> ⓘ
A reference to the chunks
Examples found in repository?
More examples
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
pub fn coalesce_nulls<'a, T: PolarsDataType>(
a: &'a ChunkedArray<T>,
b: &'a ChunkedArray<T>,
) -> (Cow<'a, ChunkedArray<T>>, Cow<'a, ChunkedArray<T>>) {
if a.null_count() > 0 || b.null_count() > 0 {
let (a, b) = align_chunks_binary(a, b);
let mut b = b.into_owned();
let a = a.coalesce_nulls(b.chunks());
for arr in a.chunks().iter() {
for arr_b in unsafe { b.chunks_mut() } {
*arr_b = arr_b.with_validity(arr.validity().cloned())
}
}
(Cow::Owned(a), Cow::Owned(b))
} else {
(Cow::Borrowed(a), Cow::Borrowed(b))
}
}
sourcepub unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef> ⓘ
pub unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef> ⓘ
A mutable reference to the chunks
Safety
The caller must ensure to not change the DataType
or length
of any of the chunks.
Examples found in repository?
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
pub fn coalesce_nulls<'a, T: PolarsDataType>(
a: &'a ChunkedArray<T>,
b: &'a ChunkedArray<T>,
) -> (Cow<'a, ChunkedArray<T>>, Cow<'a, ChunkedArray<T>>) {
if a.null_count() > 0 || b.null_count() > 0 {
let (a, b) = align_chunks_binary(a, b);
let mut b = b.into_owned();
let a = a.coalesce_nulls(b.chunks());
for arr in a.chunks().iter() {
for arr_b in unsafe { b.chunks_mut() } {
*arr_b = arr_b.with_validity(arr.validity().cloned())
}
}
(Cow::Owned(a), Cow::Owned(b))
} else {
(Cow::Borrowed(a), Cow::Borrowed(b))
}
}
sourcepub fn is_optimal_aligned(&self) -> bool
pub fn is_optimal_aligned(&self) -> bool
Returns true if contains a single chunk and has no null values
sourcepub fn null_count(&self) -> usize
pub fn null_count(&self) -> usize
Count the null values.
Examples found in repository?
More examples
101 102 103 104 105 106 107 108 109 110 111 112 113 114
pub fn argsort(&self, options: SortOptions) -> IdxCa {
if self.use_lexical_sort() {
let iters = [self.iter_str()];
argsort::argsort(
self.name(),
iters,
options,
self.logical().null_count(),
self.len(),
)
} else {
self.logical().argsort(options)
}
}
- src/functions.rs
- src/utils/mod.rs
- src/chunked_array/strings/encoding.rs
- src/chunked_array/list/iterator.rs
- src/chunked_array/ops/take/take_chunked.rs
- src/chunked_array/logical/categorical/ops/append.rs
- src/frame/hash_join/single_keys_dispatch.rs
- src/chunked_array/iterator/mod.rs
- src/chunked_array/cast.rs
- src/frame/groupby/aggregations/mod.rs
- src/chunked_array/ops/aggregate.rs
- src/chunked_array/ops/unique/mod.rs
- src/chunked_array/ndarray.rs
- src/chunked_array/ops/sort/mod.rs
- src/chunked_array/comparison.rs
- src/chunked_array/ops/take/mod.rs
- src/chunked_array/ops/is_in.rs
sourcepub fn is_null(&self) -> BooleanChunked
pub fn is_null(&self) -> BooleanChunked
Get a mask of the null values.
Examples found in repository?
More examples
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
fn fill_null_with_values(&self, value: bool) -> PolarsResult<Self> {
self.set(&self.is_null(), Some(value))
}
}
impl ChunkFillNull for Utf8Chunked {
fn fill_null(&self, strategy: FillNullStrategy) -> PolarsResult<Self> {
// nothing to fill
if !self.has_validity() {
return Ok(self.clone());
}
match strategy {
FillNullStrategy::Forward(limit) => {
let mut out: Self = match limit {
Some(limit) => impl_fill_forward_limit!(self, limit),
None => impl_fill_forward!(self),
};
out.rename(self.name());
Ok(out)
}
FillNullStrategy::Backward(limit) => {
let mut out = match limit {
None => impl_fill_backward!(self, Utf8Chunked),
Some(limit) => fill_backward_limit_utf8(self, limit),
};
out.rename(self.name());
Ok(out)
}
strat => Err(PolarsError::InvalidOperation(
format!("Strategy {strat:?} not supported").into(),
)),
}
}
}
impl ChunkFillNullValue<&str> for Utf8Chunked {
fn fill_null_with_values(&self, value: &str) -> PolarsResult<Self> {
self.set(&self.is_null(), Some(value))
}
sourcepub fn is_not_null(&self) -> BooleanChunked
pub fn is_not_null(&self) -> BooleanChunked
Get a mask of the valid values.
Examples found in repository?
More examples
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
fn not_equal(&self, rhs: &ChunkedArray<T>) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
self.not_equal(value)
} else {
self.is_not_null()
}
}
(1, _) => {
if let Some(value) = self.get(0) {
rhs.not_equal(value)
} else {
self.is_not_null()
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
lhs.comparison(&rhs, |x, y| comparison::neq_and_validity(x, y))
}
}
}
fn gt(&self, rhs: &ChunkedArray<T>) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
self.gt(value)
} else {
BooleanChunked::full("", false, self.len())
}
}
(1, _) => {
if let Some(value) = self.get(0) {
rhs.lt(value)
} else {
BooleanChunked::full("", false, rhs.len())
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
lhs.comparison(&rhs, |x, y| comparison::gt(x, y))
}
}
}
fn gt_eq(&self, rhs: &ChunkedArray<T>) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
self.gt_eq(value)
} else {
BooleanChunked::full("", false, self.len())
}
}
(1, _) => {
if let Some(value) = self.get(0) {
rhs.lt_eq(value)
} else {
BooleanChunked::full("", false, rhs.len())
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
lhs.comparison(&rhs, |x, y| comparison::gt_eq(x, y))
}
}
}
fn lt(&self, rhs: &ChunkedArray<T>) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
self.lt(value)
} else {
BooleanChunked::full("", false, self.len())
}
}
(1, _) => {
if let Some(value) = self.get(0) {
rhs.gt(value)
} else {
BooleanChunked::full("", false, rhs.len())
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
lhs.comparison(&rhs, |x, y| comparison::lt(x, y))
}
}
}
fn lt_eq(&self, rhs: &ChunkedArray<T>) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
self.lt_eq(value)
} else {
BooleanChunked::full("", false, self.len())
}
}
(1, _) => {
if let Some(value) = self.get(0) {
rhs.gt_eq(value)
} else {
BooleanChunked::full("", false, rhs.len())
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
lhs.comparison(&rhs, |x, y| comparison::lt_eq(x, y))
}
}
}
}
fn compare_bools(
lhs: &BooleanChunked,
rhs: &BooleanChunked,
f: impl Fn(&BooleanArray, &BooleanArray) -> BooleanArray,
) -> BooleanChunked {
let chunks = lhs
.downcast_iter()
.zip(rhs.downcast_iter())
.map(|(l, r)| Box::new(f(l, r)) as ArrayRef)
.collect();
BooleanChunked::from_chunks(lhs.name(), chunks)
}
impl ChunkCompare<&BooleanChunked> for BooleanChunked {
type Item = BooleanChunked;
fn equal(&self, rhs: &BooleanChunked) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
match value {
true => {
if self.null_count() == 0 {
self.clone()
} else {
let chunks = self
.downcast_iter()
.map(|arr| {
if let Some(validity) = arr.validity() {
Box::new(BooleanArray::from_data_default(
arr.values() & validity,
None,
))
as ArrayRef
} else {
Box::new(arr.clone())
}
})
.collect();
BooleanChunked::from_chunks("", chunks)
}
}
false => {
if self.null_count() == 0 {
self.not()
} else {
let chunks = self
.downcast_iter()
.map(|arr| {
let bitmap = if let Some(validity) = arr.validity() {
arr.values() ^ validity
} else {
arr.values().not()
};
Box::new(BooleanArray::from_data_default(bitmap, None))
as ArrayRef
})
.collect();
BooleanChunked::from_chunks("", chunks)
}
}
}
} else {
self.is_null()
}
}
(1, _) => rhs.equal(self),
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
compare_bools(&lhs, &rhs, |lhs, rhs| comparison::eq_and_validity(lhs, rhs))
}
}
}
fn not_equal(&self, rhs: &BooleanChunked) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
match value {
true => {
if self.null_count() == 0 {
self.not()
} else {
let chunks = self
.downcast_iter()
.map(|arr| {
let bitmap = if let Some(validity) = arr.validity() {
(arr.values() & validity).not()
} else {
arr.values().not()
};
Box::new(BooleanArray::from_data_default(bitmap, None))
as ArrayRef
})
.collect();
BooleanChunked::from_chunks("", chunks)
}
}
false => {
if self.null_count() == 0 {
self.clone()
} else {
let chunks = self
.downcast_iter()
.map(|arr| {
let bitmap = if let Some(validity) = arr.validity() {
(arr.values() ^ validity).not()
} else {
arr.values().clone()
};
Box::new(BooleanArray::from_data_default(bitmap, None))
as ArrayRef
})
.collect();
BooleanChunked::from_chunks("", chunks)
}
}
}
} else {
self.is_not_null()
}
}
(1, _) => rhs.not_equal(self),
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
compare_bools(&lhs, &rhs, |lhs, rhs| {
comparison::neq_and_validity(lhs, rhs)
})
}
}
}
fn gt(&self, rhs: &BooleanChunked) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
match value {
true => BooleanChunked::full("", false, self.len()),
false => self.clone(),
}
} else {
BooleanChunked::full("", false, self.len())
}
}
(1, _) => {
if let Some(value) = self.get(0) {
match value {
true => rhs.not(),
false => BooleanChunked::full("", false, rhs.len()),
}
} else {
BooleanChunked::full("", false, rhs.len())
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
compare_bools(&lhs, &rhs, |lhs, rhs| comparison::gt(lhs, rhs))
}
}
}
fn gt_eq(&self, rhs: &BooleanChunked) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
match value {
true => self.clone(),
false => BooleanChunked::full("", true, self.len()),
}
} else {
BooleanChunked::full("", false, self.len())
}
}
(1, _) => {
if let Some(value) = self.get(0) {
match value {
true => BooleanChunked::full("", true, rhs.len()),
false => rhs.not(),
}
} else {
BooleanChunked::full("", false, rhs.len())
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
compare_bools(&lhs, &rhs, |lhs, rhs| comparison::gt_eq(lhs, rhs))
}
}
}
fn lt(&self, rhs: &BooleanChunked) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
match value {
true => self.not(),
false => BooleanChunked::full("", false, self.len()),
}
} else {
BooleanChunked::full("", false, self.len())
}
}
(1, _) => {
if let Some(value) = self.get(0) {
match value {
true => BooleanChunked::full("", false, rhs.len()),
false => rhs.clone(),
}
} else {
BooleanChunked::full("", false, rhs.len())
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
compare_bools(&lhs, &rhs, |lhs, rhs| comparison::lt(lhs, rhs))
}
}
}
fn lt_eq(&self, rhs: &BooleanChunked) -> BooleanChunked {
// broadcast
match (self.len(), rhs.len()) {
(_, 1) => {
if let Some(value) = rhs.get(0) {
match value {
true => BooleanChunked::full("", true, self.len()),
false => BooleanChunked::full("", false, self.len()),
}
} else {
BooleanChunked::full("", false, self.len())
}
}
(1, _) => {
if let Some(value) = self.get(0) {
match value {
true => rhs.clone(),
false => BooleanChunked::full("", true, rhs.len()),
}
} else {
BooleanChunked::full("", false, rhs.len())
}
}
_ => {
// same length
let (lhs, rhs) = align_chunks_binary(self, rhs);
compare_bools(&lhs, &rhs, |lhs, rhs| comparison::lt_eq(lhs, rhs))
}
}
}
}
impl Utf8Chunked {
fn comparison(
&self,
rhs: &Utf8Chunked,
f: impl Fn(&Utf8Array<i64>, &Utf8Array<i64>) -> BooleanArray,
) -> BooleanChunked {
let chunks = self
.downcast_iter()
.zip(rhs.downcast_iter())
.map(|(left, right)| {
let arr = f(left, right);
Box::new(arr) as ArrayRef
})
.collect();
BooleanChunked::from_chunks("", chunks)
}
}
impl ChunkCompare<&Utf8Chunked> for Utf8Chunked {
type Item = BooleanChunked;
fn equal(&self, rhs: &Utf8Chunked) -> BooleanChunked {
// broadcast
if rhs.len() == 1 {
if let Some(value) = rhs.get(0) {
self.equal(value)
} else {
self.is_null()
}
} else if self.len() == 1 {
if let Some(value) = self.get(0) {
rhs.equal(value)
} else {
self.is_null()
}
} else {
let (lhs, rhs) = align_chunks_binary(self, rhs);
lhs.comparison(&rhs, comparison::utf8::eq_and_validity)
}
}
fn not_equal(&self, rhs: &Utf8Chunked) -> BooleanChunked {
// broadcast
if rhs.len() == 1 {
if let Some(value) = rhs.get(0) {
self.not_equal(value)
} else {
self.is_not_null()
}
} else if self.len() == 1 {
if let Some(value) = self.get(0) {
rhs.not_equal(value)
} else {
self.is_not_null()
}
} else {
let (lhs, rhs) = align_chunks_binary(self, rhs);
lhs.comparison(&rhs, comparison::utf8::neq_and_validity)
}
}
sourcepub fn dtype(&self) -> &DataType
pub fn dtype(&self) -> &DataType
Get data type of ChunkedArray.
Examples found in repository?
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
fn _dtype(&self) -> &DataType {
self.0.dtype()
}
unsafe fn agg_list(&self, groups: &GroupsProxy) -> Series {
self.0.agg_list(groups)
}
fn into_partial_eq_inner<'a>(&'a self) -> Box<dyn PartialEqInner + 'a> {
(&self.0).into_partial_eq_inner()
}
fn vec_hash(&self, random_state: RandomState, buf: &mut Vec<u64>) -> PolarsResult<()> {
self.0.vec_hash(random_state, buf);
Ok(())
}
fn vec_hash_combine(&self, build_hasher: RandomState, hashes: &mut [u64]) -> PolarsResult<()> {
self.0.vec_hash_combine(build_hasher, hashes);
Ok(())
}
fn group_tuples(&self, multithreaded: bool, sorted: bool) -> PolarsResult<GroupsProxy> {
IntoGroupsProxy::group_tuples(&self.0, multithreaded, sorted)
}
#[cfg(feature = "zip_with")]
fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
self.0
.zip_with(mask, other.as_ref().as_ref())
.map(|ca| ca.into_series())
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "object")))]
impl<T> SeriesTrait for SeriesWrap<ObjectChunked<T>>
where
T: PolarsObject,
{
fn rename(&mut self, name: &str) {
ObjectChunked::rename(&mut self.0, name)
}
fn chunk_lengths(&self) -> ChunkIdIter {
ObjectChunked::chunk_id(&self.0)
}
fn name(&self) -> &str {
ObjectChunked::name(&self.0)
}
fn dtype(&self) -> &DataType {
ObjectChunked::dtype(&self.0)
}
More examples
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
fn append(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
self.0.append(other.as_ref().as_ref())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot append Series; data types don't match".into(),
))
}
}
fn extend(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
self.0.extend(other.as_ref().as_ref())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot extend Series; data types don't match".into(),
))
}
}
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
fn append(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
self.0.append(other.as_ref().as_ref());
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot append Series; data types don't match".into(),
))
}
}
fn extend(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
self.0.extend(other.as_ref().as_ref());
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot extend Series; data types don't match".into(),
))
}
}
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
fn append(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
// todo! add object
self.0.append(other.as_ref().as_ref());
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot append Series; data types don't match".into(),
))
}
}
fn extend(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
self.0.extend(other.as_ref().as_ref());
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot extend Series; data types don't match".into(),
))
}
}
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
unsafe fn equal_element(&self, idx_self: usize, idx_other: usize, other: &Series) -> bool {
let ca_other = other.as_ref().as_ref();
debug_assert!(self.dtype() == other.dtype());
let ca_other = &*(ca_other as *const ChunkedArray<T>);
// Should be get and not get_unchecked, because there could be nulls
self.get(idx_self) == ca_other.get(idx_other)
}
}
impl ChunkEqualElement for BooleanChunked {
unsafe fn equal_element(&self, idx_self: usize, idx_other: usize, other: &Series) -> bool {
let ca_other = other.as_ref().as_ref();
debug_assert!(self.dtype() == other.dtype());
let ca_other = &*(ca_other as *const BooleanChunked);
self.get(idx_self) == ca_other.get(idx_other)
}
}
impl ChunkEqualElement for Utf8Chunked {
unsafe fn equal_element(&self, idx_self: usize, idx_other: usize, other: &Series) -> bool {
let ca_other = other.as_ref().as_ref();
debug_assert!(self.dtype() == other.dtype());
let ca_other = &*(ca_other as *const Utf8Chunked);
self.get(idx_self) == ca_other.get(idx_other)
}
- src/chunked_array/drop.rs
- src/chunked_array/ops/append.rs
- src/chunked_array/ops/unique/mod.rs
- src/chunked_array/ops/chunkops.rs
- src/chunked_array/mod.rs
- src/chunked_array/ops/filter.rs
- src/chunked_array/cast.rs
- src/chunked_array/ops/aggregate.rs
- src/chunked_array/ops/bit_repr.rs
- src/frame/groupby/into_groups.rs
- src/chunked_array/ops/is_in.rs
- src/chunked_array/ops/rolling_window.rs
sourcepub fn name(&self) -> &str
pub fn name(&self) -> &str
Name of the ChunkedArray.
Examples found in repository?
More examples
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
fn name(&self) -> &str {
self.0.logical().name()
}
fn chunks(&self) -> &Vec<ArrayRef> {
self.0.logical().chunks()
}
fn shrink_to_fit(&mut self) {
self.0.logical_mut().shrink_to_fit()
}
fn slice(&self, offset: i64, length: usize) -> Series {
self.with_state(false, |cats| cats.slice(offset, length))
.into_series()
}
fn append(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
self.0.append(other.categorical().unwrap())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot append Series; data types don't match".into(),
))
}
}
fn extend(&mut self, other: &Series) -> PolarsResult<()> {
if self.0.dtype() == other.dtype() {
let other = other.categorical()?;
self.0.logical_mut().extend(other.logical());
let new_rev_map = self.0.merge_categorical_map(other)?;
// safety:
// rev_maps are merged
unsafe { self.0.set_rev_map(new_rev_map, false) };
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot extend Series; data types don't match".into(),
))
}
}
fn filter(&self, filter: &BooleanChunked) -> PolarsResult<Series> {
self.try_with_state(false, |cats| cats.filter(filter))
.map(|ca| ca.into_series())
}
#[cfg(feature = "chunked_ids")]
unsafe fn _take_chunked_unchecked(&self, by: &[ChunkId], sorted: IsSorted) -> Series {
let cats = self.0.logical().take_chunked_unchecked(by, sorted);
self.finish_with_state(false, cats).into_series()
}
#[cfg(feature = "chunked_ids")]
unsafe fn _take_opt_chunked_unchecked(&self, by: &[Option<ChunkId>]) -> Series {
let cats = self.0.logical().take_opt_chunked_unchecked(by);
self.finish_with_state(false, cats).into_series()
}
fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
let indices = if indices.chunks.len() > 1 {
Cow::Owned(indices.rechunk())
} else {
Cow::Borrowed(indices)
};
self.try_with_state(false, |cats| cats.take((&*indices).into()))
.map(|ca| ca.into_series())
}
fn take_iter(&self, iter: &mut dyn TakeIterator) -> PolarsResult<Series> {
let cats = self.0.logical().take(iter.into())?;
Ok(self.finish_with_state(false, cats).into_series())
}
fn take_every(&self, n: usize) -> Series {
self.with_state(true, |cats| cats.take_every(n))
.into_series()
}
unsafe fn take_iter_unchecked(&self, iter: &mut dyn TakeIterator) -> Series {
let cats = self.0.logical().take_unchecked(iter.into());
self.finish_with_state(false, cats).into_series()
}
unsafe fn take_unchecked(&self, idx: &IdxCa) -> PolarsResult<Series> {
let idx = if idx.chunks.len() > 1 {
Cow::Owned(idx.rechunk())
} else {
Cow::Borrowed(idx)
};
Ok(self
.with_state(false, |cats| cats.take_unchecked((&*idx).into()))
.into_series())
}
unsafe fn take_opt_iter_unchecked(&self, iter: &mut dyn TakeIteratorNulls) -> Series {
let cats = self.0.logical().take_unchecked(iter.into());
self.finish_with_state(false, cats).into_series()
}
#[cfg(feature = "take_opt_iter")]
fn take_opt_iter(&self, iter: &mut dyn TakeIteratorNulls) -> PolarsResult<Series> {
let cats = self.0.logical().take(iter.into())?;
Ok(self.finish_with_state(false, cats).into_series())
}
fn len(&self) -> usize {
self.0.len()
}
fn rechunk(&self) -> Series {
self.with_state(true, |ca| ca.rechunk()).into_series()
}
fn new_from_index(&self, index: usize, length: usize) -> Series {
self.with_state(true, |cats| cats.new_from_index(index, length))
.into_series()
}
fn cast(&self, data_type: &DataType) -> PolarsResult<Series> {
self.0.cast(data_type)
}
fn get(&self, index: usize) -> PolarsResult<AnyValue> {
self.0.get_any_value(index)
}
#[inline]
#[cfg(feature = "private")]
unsafe fn get_unchecked(&self, index: usize) -> AnyValue {
self.0.get_any_value_unchecked(index)
}
fn sort_with(&self, options: SortOptions) -> Series {
self.0.sort_with(options).into_series()
}
fn argsort(&self, options: SortOptions) -> IdxCa {
self.0.argsort(options)
}
fn null_count(&self) -> usize {
self.0.logical().null_count()
}
fn has_validity(&self) -> bool {
self.0.logical().has_validity()
}
fn unique(&self) -> PolarsResult<Series> {
self.0.unique().map(|ca| ca.into_series())
}
fn n_unique(&self) -> PolarsResult<usize> {
self.0.n_unique()
}
fn arg_unique(&self) -> PolarsResult<IdxCa> {
self.0.logical().arg_unique()
}
fn is_null(&self) -> BooleanChunked {
self.0.logical().is_null()
}
fn is_not_null(&self) -> BooleanChunked {
self.0.logical().is_not_null()
}
fn is_unique(&self) -> PolarsResult<BooleanChunked> {
self.0.logical().is_unique()
}
fn is_duplicated(&self) -> PolarsResult<BooleanChunked> {
self.0.logical().is_duplicated()
}
fn reverse(&self) -> Series {
self.with_state(true, |cats| cats.reverse()).into_series()
}
fn as_single_ptr(&mut self) -> PolarsResult<usize> {
self.0.logical_mut().as_single_ptr()
}
fn shift(&self, periods: i64) -> Series {
self.with_state(false, |ca| ca.shift(periods)).into_series()
}
fn fill_null(&self, strategy: FillNullStrategy) -> PolarsResult<Series> {
self.try_with_state(false, |cats| cats.fill_null(strategy))
.map(|ca| ca.into_series())
}
fn _sum_as_series(&self) -> Series {
CategoricalChunked::full_null(self.0.logical().name(), 1).into_series()
}
fn max_as_series(&self) -> Series {
CategoricalChunked::full_null(self.0.logical().name(), 1).into_series()
}
fn min_as_series(&self) -> Series {
CategoricalChunked::full_null(self.0.logical().name(), 1).into_series()
}
fn median_as_series(&self) -> Series {
CategoricalChunked::full_null(self.0.logical().name(), 1).into_series()
}
fn var_as_series(&self, _ddof: u8) -> Series {
CategoricalChunked::full_null(self.0.logical().name(), 1).into_series()
}
fn std_as_series(&self, _ddof: u8) -> Series {
CategoricalChunked::full_null(self.0.logical().name(), 1).into_series()
}
fn quantile_as_series(
&self,
_quantile: f64,
_interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
Ok(CategoricalChunked::full_null(self.0.logical().name(), 1).into_series())
}
fn fmt_list(&self) -> String {
FmtList::fmt_list(&self.0)
}
fn clone_inner(&self) -> Arc<dyn SeriesTrait> {
Arc::new(SeriesWrap(Clone::clone(&self.0)))
}
#[cfg(feature = "is_in")]
fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked> {
_check_categorical_src(self.dtype(), other.dtype())?;
self.0.logical().is_in(&other.to_physical_repr())
}
#[cfg(feature = "repeat_by")]
fn repeat_by(&self, by: &IdxCa) -> ListChunked {
let out = self.0.logical().repeat_by(by);
let casted = out
.cast(&DataType::List(Box::new(self.dtype().clone())))
.unwrap();
casted.list().unwrap().clone()
}
#[cfg(feature = "is_first")]
fn is_first(&self) -> PolarsResult<BooleanChunked> {
self.0.logical().is_first()
}
#[cfg(feature = "mode")]
fn mode(&self) -> PolarsResult<Series> {
Ok(CategoricalChunked::full_null(self.0.logical().name(), 1).into_series())
}
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
pub(crate) fn field(&self) -> Field {
let name = self.logical().name();
Field::new(name, self.dtype().clone())
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.logical.len()
}
pub fn name(&self) -> &str {
self.logical.name()
}
/// Get a reference to the logical array (the categories).
pub fn logical(&self) -> &UInt32Chunked {
&self.logical
}
/// Get a reference to the logical array (the categories).
pub(crate) fn logical_mut(&mut self) -> &mut UInt32Chunked {
&mut self.logical
}
/// Build a categorical from an original RevMap. That means that the number of categories in the `RevMapping == self.unique().len()`.
pub(crate) fn from_chunks_original(
name: &str,
chunks: Vec<ArrayRef>,
rev_map: RevMapping,
) -> Self {
let ca = UInt32Chunked::from_chunks(name, chunks);
let mut logical = Logical::<UInt32Type, _>::new_logical::<CategoricalType>(ca);
logical.2 = Some(DataType::Categorical(Some(Arc::new(rev_map))));
let bit_settings = 1u8;
Self {
logical,
bit_settings,
}
}
pub fn set_lexical_sorted(&mut self, toggle: bool) {
if toggle {
self.bit_settings |= 1u8 << 1;
} else {
self.bit_settings &= !(1u8 << 1);
}
}
pub(crate) fn use_lexical_sort(&self) -> bool {
self.bit_settings & 1 << 1 != 0
}
/// Create a [`CategoricalChunked`] from an array of `idx` and an existing [`RevMapping`]: `rev_map`.
///
/// # Safety
/// Invariant in `v < rev_map.len() for v in idx` must be hold.
pub unsafe fn from_cats_and_rev_map_unchecked(
idx: UInt32Chunked,
rev_map: Arc<RevMapping>,
) -> Self {
let mut logical = Logical::<UInt32Type, _>::new_logical::<CategoricalType>(idx);
logical.2 = Some(DataType::Categorical(Some(rev_map)));
Self {
logical,
bit_settings: Default::default(),
}
}
/// # Safety
/// The existing index values must be in bounds of the new [`RevMapping`].
pub(crate) unsafe fn set_rev_map(&mut self, rev_map: Arc<RevMapping>, keep_fast_unique: bool) {
self.logical.2 = Some(DataType::Categorical(Some(rev_map)));
if !keep_fast_unique {
self.set_fast_unique(false)
}
}
pub(crate) fn can_fast_unique(&self) -> bool {
self.bit_settings & 1 << 0 != 0 && self.logical.chunks.len() == 1
}
pub(crate) fn set_fast_unique(&mut self, can: bool) {
if can {
self.bit_settings |= 1u8 << 0;
} else {
self.bit_settings &= !(1u8 << 0);
}
}
/// Get a reference to the mapping of categorical types to the string values.
pub fn get_rev_map(&self) -> &Arc<RevMapping> {
if let DataType::Categorical(Some(rev_map)) = &self.logical.2.as_ref().unwrap() {
rev_map
} else {
panic!("implementation error")
}
}
/// Create an `[Iterator]` that iterates over the `&str` values of the `[CategoricalChunked]`.
pub fn iter_str(&self) -> CatIter<'_> {
let iter = self.logical().into_iter();
CatIter {
rev: self.get_rev_map(),
iter,
}
}
}
impl LogicalType for CategoricalChunked {
fn dtype(&self) -> &DataType {
self.logical.2.as_ref().unwrap()
}
fn get_any_value(&self, i: usize) -> PolarsResult<AnyValue<'_>> {
if i < self.len() {
Ok(unsafe { self.get_any_value_unchecked(i) })
} else {
Err(PolarsError::ComputeError("Index is out of bounds.".into()))
}
}
unsafe fn get_any_value_unchecked(&self, i: usize) -> AnyValue<'_> {
match self.logical.0.get_unchecked(i) {
Some(i) => AnyValue::Categorical(i, self.get_rev_map()),
None => AnyValue::Null,
}
}
fn cast(&self, dtype: &DataType) -> PolarsResult<Series> {
match dtype {
DataType::Utf8 => {
let mapping = &**self.get_rev_map();
let mut builder =
Utf8ChunkedBuilder::new(self.logical.name(), self.len(), self.len() * 5);
let f = |idx: u32| mapping.get(idx);
if !self.logical.has_validity() {
self.logical
.into_no_null_iter()
.for_each(|idx| builder.append_value(f(idx)));
} else {
self.logical.into_iter().for_each(|opt_idx| {
builder.append_option(opt_idx.map(f));
});
}
let ca = builder.finish();
Ok(ca.into_series())
}
DataType::UInt32 => {
let ca =
UInt32Chunked::from_chunks(self.logical.name(), self.logical.chunks.clone());
Ok(ca.into_series())
}
#[cfg(feature = "dtype-categorical")]
DataType::Categorical(_) => Ok(self.clone().into_series()),
_ => self.logical.cast(dtype),
}
}
- src/chunked_array/ops/concat_str.rs
- src/fmt.rs
- src/chunked_array/ops/aggregate.rs
- src/chunked_array/float.rs
- src/chunked_array/ops/mod.rs
- src/chunked_array/ops/take/take_every.rs
- src/chunked_array/ops/take/take_single.rs
- src/chunked_array/comparison.rs
- src/chunked_array/ops/cum_agg.rs
- src/chunked_array/ops/append.rs
- src/chunked_array/ops/apply.rs
- src/chunked_array/ops/reverse.rs
- src/chunked_array/ops/take/take_random.rs
- src/chunked_array/ops/repeat_by.rs
- src/chunked_array/mod.rs
- src/chunked_array/ops/filter.rs
- src/chunked_array/list/iterator.rs
- src/chunked_array/bitwise.rs
- src/chunked_array/ops/zip.rs
- src/chunked_array/ops/shift.rs
- src/chunked_array/ops/chunkops.rs
- src/chunked_array/ops/is_in.rs
- src/chunked_array/ops/take/take_chunked.rs
- src/chunked_array/logical/categorical/ops/unique.rs
- src/chunked_array/object/extension/list.rs
- src/chunked_array/cast.rs
- src/chunked_array/arithmetic.rs
- src/chunked_array/ops/set.rs
- src/chunked_array/ops/unique/mod.rs
- src/chunked_array/ops/bit_repr.rs
- src/chunked_array/ops/fill_null.rs
- src/chunked_array/ops/sort/mod.rs
- src/chunked_array/ops/take/mod.rs
- src/chunked_array/ops/explode.rs
- src/chunked_array/ops/rolling_window.rs
- src/frame/groupby/aggregations/agg_list.rs
sourcepub fn ref_field(&self) -> &Field
pub fn ref_field(&self) -> &Field
Get a reference to the field.
Examples found in repository?
More examples
sourcepub fn rename(&mut self, name: &str)
pub fn rename(&mut self, name: &str)
Rename this ChunkedArray.
Examples found in repository?
More examples
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
fn sum_as_series(&self) -> Series {
let v = self.sum();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = self.max();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = self.min();
let mut ca: ChunkedArray<T> = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn prod_as_series(&self) -> Series {
let mut prod = None;
for opt_v in self.into_iter() {
match (prod, opt_v) {
(_, None) => return Self::full_null(self.name(), 1).into_series(),
(None, Some(v)) => prod = Some(v),
(Some(p), Some(v)) => prod = Some(p * v),
}
}
Self::from_slice_options(self.name(), &[prod]).into_series()
}
}
macro_rules! impl_as_series {
($self:expr, $agg:ident, $ty: ty) => {{
let v = $self.$agg();
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
($self:expr, $agg:ident, $arg:expr, $ty: ty) => {{
let v = $self.$agg($arg);
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
ca.into_series()
}};
}
impl<T> VarAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
impl VarAggSeries for Float32Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float32Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float32Chunked)
}
}
impl VarAggSeries for Float64Chunked {
fn var_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, var, ddof, Float64Chunked)
}
fn std_as_series(&self, ddof: u8) -> Series {
impl_as_series!(self, std, ddof, Float64Chunked)
}
}
macro_rules! impl_quantile_as_series {
($self:expr, $agg:ident, $ty: ty, $qtl:expr, $opt:expr) => {{
let v = $self.$agg($qtl, $opt)?;
let mut ca: $ty = [v].iter().copied().collect();
ca.rename($self.name());
Ok(ca.into_series())
}};
}
impl<T> QuantileAggSeries for ChunkedArray<T>
where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd>
+ compute::aggregate::Sum<T::Native>
+ compute::aggregate::SimdOrd<T::Native>,
{
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl QuantileAggSeries for Float32Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float32Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float32Chunked)
}
}
impl QuantileAggSeries for Float64Chunked {
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> PolarsResult<Series> {
impl_quantile_as_series!(self, quantile, Float64Chunked, quantile, interpol)
}
fn median_as_series(&self) -> Series {
impl_as_series!(self, median, Float64Chunked)
}
}
impl ChunkAggSeries for BooleanChunked {
fn sum_as_series(&self) -> Series {
let v = ChunkAgg::sum(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn max_as_series(&self) -> Series {
let v = ChunkAgg::max(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
fn min_as_series(&self) -> Series {
let v = ChunkAgg::min(self);
let mut ca: IdxCa = [v].iter().copied().collect();
ca.rename(self.name());
ca.into_series()
}
- src/chunked_array/ops/full.rs
- src/chunked_array/builder/mod.rs
- src/chunked_array/cast.rs
- src/chunked_array/ops/take/take_every.rs
- src/frame/groupby/mod.rs
- src/chunked_array/ops/cum_agg.rs
- src/frame/groupby/proxy.rs
- src/chunked_array/ops/apply.rs
- src/chunked_array/ops/reverse.rs
- src/chunked_array/ops/zip.rs
- src/chunked_array/logical/categorical/ops/unique.rs
- src/chunked_array/list/iterator.rs
- src/chunked_array/ops/sort/mod.rs
- src/chunked_array/ops/is_in.rs
- src/chunked_array/ops/take/take_chunked.rs
- src/chunked_array/bitwise.rs
- src/chunked_array/arithmetic.rs
- src/series/comparison.rs
- src/chunked_array/ops/fill_null.rs
- src/chunked_array/ops/take/mod.rs
source§impl<T> ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkedArray<T>where
T: PolarsNumericType,
sourcepub fn cont_slice(&self) -> PolarsResult<&[T::Native]>
pub fn cont_slice(&self) -> PolarsResult<&[T::Native]>
Contiguous slice
Examples found in repository?
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
pub fn to_ndarray(&self) -> PolarsResult<ArrayView1<T::Native>> {
let slice = self.cont_slice()?;
Ok(aview1(slice))
}
}
impl ListChunked {
/// If all nested `Series` have the same length, a 2 dimensional `ndarray::Array` is returned.
#[cfg_attr(docsrs, doc(cfg(feature = "ndarray")))]
pub fn to_ndarray<N>(&self) -> PolarsResult<Array2<N::Native>>
where
N: PolarsNumericType,
{
if self.null_count() != 0 {
Err(PolarsError::ComputeError(
"Creation of ndarray with null values is not supported.".into(),
))
} else {
let mut iter = self.into_no_null_iter();
let mut ndarray;
let width;
// first iteration determine the size
if let Some(series) = iter.next() {
width = series.len();
let mut row_idx = 0;
ndarray = ndarray::Array::uninit((self.len(), width));
let series = series.cast(&N::get_dtype())?;
let ca = series.unpack::<N>()?;
let a = ca.to_ndarray()?;
let mut row = ndarray.slice_mut(s![row_idx, ..]);
a.assign_to(&mut row);
row_idx += 1;
for series in iter {
if series.len() != width {
return Err(PolarsError::ShapeMisMatch(
"Could not create a 2D array. Series have different lengths".into(),
));
}
let series = series.cast(&N::get_dtype())?;
let ca = series.unpack::<N>()?;
let a = ca.to_ndarray()?;
let mut row = ndarray.slice_mut(s![row_idx, ..]);
a.assign_to(&mut row);
row_idx += 1;
}
debug_assert_eq!(row_idx, self.len());
// Safety:
// We have assigned to every row and element of the array
unsafe { Ok(ndarray.assume_init()) }
} else {
Err(PolarsError::NoData(
"cannot create ndarray of empty ListChunked".into(),
))
}
}
}
}
impl DataFrame {
/// Create a 2D `ndarray::Array` from this `DataFrame`. This requires all columns in the
/// `DataFrame` to be non-null and numeric. They will be casted to the same data type
/// (if they aren't already).
///
/// For floating point data we implicitly convert `None` to `NaN` without failure.
///
/// ```rust
/// use polars_core::prelude::*;
/// let a = UInt32Chunked::new("a", &[1, 2, 3]).into_series();
/// let b = Float64Chunked::new("b", &[10., 8., 6.]).into_series();
///
/// let df = DataFrame::new(vec![a, b]).unwrap();
/// let ndarray = df.to_ndarray::<Float64Type>().unwrap();
/// println!("{:?}", ndarray);
/// ```
/// Outputs:
/// ```text
/// [[1.0, 10.0],
/// [2.0, 8.0],
/// [3.0, 6.0]], shape=[3, 2], strides=[2, 1], layout=C (0x1), const ndim=2/
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "ndarray")))]
pub fn to_ndarray<N>(&self) -> PolarsResult<Array2<N::Native>>
where
N: PolarsNumericType,
{
let columns = self
.get_columns()
.par_iter()
.map(|s| {
let s = s.cast(&N::get_dtype())?;
let s = match s.dtype() {
DataType::Float32 => {
let ca = s.f32().unwrap();
ca.none_to_nan().into_series()
}
DataType::Float64 => {
let ca = s.f64().unwrap();
ca.none_to_nan().into_series()
}
_ => s,
};
Ok(s.rechunk())
})
.collect::<PolarsResult<Vec<_>>>()?;
let shape = self.shape();
let height = self.height();
let mut membuf = Vec::with_capacity(shape.0 * shape.1);
let ptr = membuf.as_ptr() as usize;
columns.par_iter().enumerate().map(|(col_idx, s)| {
if s.null_count() != 0 {
return Err(PolarsError::ComputeError(
"Creation of ndarray with null values is not supported. Consider using floats and NaNs".into(),
));
}
// this is an Arc clone if already of type N
let s = s.cast(&N::get_dtype())?;
let ca = s.unpack::<N>()?;
let vals = ca.cont_slice().unwrap();
// Safety:
// we get parallel access to the vector
// but we make sure that we don't get aliased access by offsetting the column indices + length
unsafe {
let offset_ptr = (ptr as *mut N::Native).add(col_idx * height) ;
// Safety:
// this is uninitialized memory, so we must never read from this data
// copy_from_slice does not read
let buf = std::slice::from_raw_parts_mut(offset_ptr, height);
buf.copy_from_slice(vals)
}
Ok(())
}).collect::<PolarsResult<Vec<_>>>()?;
// Safety:
// we have written all data, so we can now safely set length
unsafe {
membuf.set_len(shape.0 * shape.1);
}
let ndarr = Array2::from_shape_vec((shape.1, shape.0), membuf).unwrap();
Ok(ndarr.reversed_axes())
}
More examples
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
fn reverse(&self) -> ChunkedArray<T> {
let mut out = if let Ok(slice) = self.cont_slice() {
let ca: NoNull<ChunkedArray<T>> = slice.iter().rev().copied().collect_trusted();
ca.into_inner()
} else {
self.into_iter().rev().collect_trusted()
};
out.rename(self.name());
match self.is_sorted2() {
IsSorted::Ascending => out.set_sorted2(IsSorted::Descending),
IsSorted::Descending => out.set_sorted2(IsSorted::Ascending),
_ => {}
}
out
}
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
pub(crate) fn join_asof(
&self,
other: &Series,
strategy: AsofStrategy,
tolerance: Option<AnyValue<'static>>,
) -> PolarsResult<Vec<Option<IdxSize>>> {
let other = self.unpack_series_matching_type(other)?;
// cont_slice requires a single chunk
let ca = self.rechunk();
let other = other.rechunk();
let out = match strategy {
AsofStrategy::Forward => match tolerance {
None => join_asof_forward(ca.cont_slice().unwrap(), other.cont_slice().unwrap()),
Some(tolerance) => {
let tolerance = tolerance.extract::<T::Native>().unwrap();
join_asof_forward_with_tolerance(
ca.cont_slice().unwrap(),
other.cont_slice().unwrap(),
tolerance,
)
}
},
AsofStrategy::Backward => match tolerance {
None => join_asof_backward(ca.cont_slice().unwrap(), other.cont_slice().unwrap()),
Some(tolerance) => {
let tolerance = tolerance.extract::<T::Native>().unwrap();
join_asof_backward_with_tolerance(
self.cont_slice().unwrap(),
other.cont_slice().unwrap(),
tolerance,
)
}
},
};
Ok(out)
}
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
fn num_groups_proxy<T>(ca: &ChunkedArray<T>, multithreaded: bool, sorted: bool) -> GroupsProxy
where
T: PolarsIntegerType,
T::Native: Hash + Eq + Send + AsU64,
Option<T::Native>: AsU64,
{
// set group size hint
#[cfg(feature = "dtype-categorical")]
let group_size_hint = if let DataType::Categorical(Some(m)) = ca.dtype() {
ca.len() / m.len()
} else {
0
};
#[cfg(not(feature = "dtype-categorical"))]
let group_size_hint = 0;
if multithreaded && group_multithreaded(ca) {
let n_partitions = _set_partition_size() as u64;
// use the arrays as iterators
if ca.chunks.len() == 1 {
if !ca.has_validity() {
let keys = vec![ca.cont_slice().unwrap()];
groupby_threaded_num(keys, group_size_hint, n_partitions, sorted)
} else {
let keys = ca
.downcast_iter()
.map(|arr| arr.into_iter().map(|x| x.copied()).collect::<Vec<_>>())
.collect::<Vec<_>>();
groupby_threaded_num(keys, group_size_hint, n_partitions, sorted)
}
// use the polars-iterators
} else if !ca.has_validity() {
let keys = vec![ca.into_no_null_iter().collect::<Vec<_>>()];
groupby_threaded_num(keys, group_size_hint, n_partitions, sorted)
} else {
let keys = vec![ca.into_iter().collect::<Vec<_>>()];
groupby_threaded_num(keys, group_size_hint, n_partitions, sorted)
}
} else if !ca.has_validity() {
groupby(ca.into_no_null_iter(), sorted)
} else {
groupby(ca.into_iter(), sorted)
}
}
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
fn asof_join_by_numeric<T, S>(
by_left: &ChunkedArray<S>,
by_right: &ChunkedArray<S>,
left_asof: &ChunkedArray<T>,
right_asof: &ChunkedArray<T>,
tolerance: Option<AnyValue<'static>>,
strategy: AsofStrategy,
) -> PolarsResult<Vec<Option<IdxSize>>>
where
T: PolarsNumericType,
S: PolarsNumericType,
S::Native: Hash + Eq + AsU64,
{
#[allow(clippy::type_complexity)]
let (join_asof_fn, tolerance, forward): (
unsafe fn(T::Native, &[T::Native], &[IdxSize], T::Native) -> (Option<IdxSize>, usize),
_,
_,
) = match (tolerance, strategy) {
(Some(tolerance), AsofStrategy::Backward) => {
let tol = tolerance.extract::<T::Native>().unwrap();
(
join_asof_backward_with_indirection_and_tolerance,
tol,
false,
)
}
(None, AsofStrategy::Backward) => (
join_asof_backward_with_indirection,
T::Native::zero(),
false,
),
(Some(tolerance), AsofStrategy::Forward) => {
let tol = tolerance.extract::<T::Native>().unwrap();
(join_asof_forward_with_indirection_and_tolerance, tol, true)
}
(None, AsofStrategy::Forward) => {
(join_asof_forward_with_indirection, T::Native::zero(), true)
}
};
let left_asof = left_asof.rechunk();
let err = |_: PolarsError| {
PolarsError::ComputeError("Keys are not allowed to have null values in asof join.".into())
};
let left_asof = left_asof.cont_slice().map_err(err)?;
let right_asof = right_asof.rechunk();
let right_asof = right_asof.cont_slice().map_err(err)?;
let n_threads = POOL.current_num_threads();
let splitted_left = split_ca(by_left, n_threads).unwrap();
let splitted_right = split_ca(by_right, n_threads).unwrap();
let vals_left = splitted_left
.iter()
.map(|ca| ca.cont_slice().unwrap())
.collect::<Vec<_>>();
let vals_right = splitted_right
.iter()
.map(|ca| ca.cont_slice().unwrap())
.collect::<Vec<_>>();
let hash_tbls = create_probe_table(vals_right);
// we determine the offset so that we later know which index to store in the join tuples
let offsets = vals_left
.iter()
.map(|ph| ph.len())
.scan(0, |state, val| {
let out = *state;
*state += val;
Some(out)
})
.collect::<Vec<_>>();
let n_tables = hash_tbls.len() as u64;
debug_assert!(n_tables.is_power_of_two());
// next we probe the right relation
Ok(POOL.install(|| {
vals_left
.into_par_iter()
.zip(offsets)
// probes_hashes: Vec<u64> processed by this thread
// offset: offset index
.map(|(vals_left, offset)| {
// local reference
let hash_tbls = &hash_tbls;
// assume the result tuples equal length of the no. of hashes processed by this thread.
let mut results = Vec::with_capacity(vals_left.len());
let mut right_tbl_offsets = PlHashMap::with_capacity(HASHMAP_INIT_SIZE);
vals_left.iter().enumerate().for_each(|(idx_a, k)| {
let idx_a = (idx_a + offset) as IdxSize;
// probe table that contains the hashed value
let current_probe_table = unsafe {
get_hash_tbl_threaded_join_partitioned(k.as_u64(), hash_tbls, n_tables)
};
// we already hashed, so we don't have to hash again.
let value = current_probe_table.get(k);
match value {
// left and right matches
Some(indexes_b) => {
process_group(
*k,
idx_a,
tolerance,
indexes_b,
&mut right_tbl_offsets,
join_asof_fn,
left_asof,
right_asof,
&mut results,
forward,
);
}
// only left values, right = null
None => results.push(None),
}
});
results
})
.flatten()
.collect()
}))
}
fn asof_join_by_utf8<T>(
by_left: &Utf8Chunked,
by_right: &Utf8Chunked,
left_asof: &ChunkedArray<T>,
right_asof: &ChunkedArray<T>,
tolerance: Option<AnyValue<'static>>,
strategy: AsofStrategy,
) -> Vec<Option<IdxSize>>
where
T: PolarsNumericType,
{
#[allow(clippy::type_complexity)]
let (join_asof_fn, tolerance, forward): (
unsafe fn(T::Native, &[T::Native], &[IdxSize], T::Native) -> (Option<IdxSize>, usize),
_,
_,
) = match (tolerance, strategy) {
(Some(tolerance), AsofStrategy::Backward) => {
let tol = tolerance.extract::<T::Native>().unwrap();
(
join_asof_backward_with_indirection_and_tolerance,
tol,
false,
)
}
(None, AsofStrategy::Backward) => (
join_asof_backward_with_indirection,
T::Native::zero(),
false,
),
(Some(tolerance), AsofStrategy::Forward) => {
let tol = tolerance.extract::<T::Native>().unwrap();
(join_asof_forward_with_indirection_and_tolerance, tol, true)
}
(None, AsofStrategy::Forward) => {
(join_asof_forward_with_indirection, T::Native::zero(), true)
}
};
let left_asof = left_asof.rechunk();
let left_asof = left_asof.cont_slice().unwrap();
let right_asof = right_asof.rechunk();
let right_asof = right_asof.cont_slice().unwrap();
let n_threads = POOL.current_num_threads();
let splitted_by_left = split_ca(by_left, n_threads).unwrap();
let splitted_right = split_ca(by_right, n_threads).unwrap();
let hb = RandomState::default();
let vals_left = prepare_strs(&splitted_by_left, &hb);
let vals_right = prepare_strs(&splitted_right, &hb);
let hash_tbls = create_probe_table(vals_right);
// we determine the offset so that we later know which index to store in the join tuples
let offsets = vals_left
.iter()
.map(|ph| ph.len())
.scan(0, |state, val| {
let out = *state;
*state += val;
Some(out)
})
.collect::<Vec<_>>();
let n_tables = hash_tbls.len() as u64;
debug_assert!(n_tables.is_power_of_two());
// next we probe the right relation
POOL.install(|| {
vals_left
.into_par_iter()
.zip(offsets)
// probes_hashes: Vec<u64> processed by this thread
// offset: offset index
.map(|(vals_left, offset)| {
// local reference
let hash_tbls = &hash_tbls;
// assume the result tuples equal length of the no. of hashes processed by this thread.
let mut results = Vec::with_capacity(vals_left.len());
let mut right_tbl_offsets = PlHashMap::with_capacity(HASHMAP_INIT_SIZE);
vals_left.iter().enumerate().for_each(|(idx_a, k)| {
let idx_a = (idx_a + offset) as IdxSize;
// probe table that contains the hashed value
let current_probe_table = unsafe {
get_hash_tbl_threaded_join_partitioned(k.as_u64(), hash_tbls, n_tables)
};
// we already hashed, so we don't have to hash again.
let value = current_probe_table.get(k);
match value {
// left and right matches
Some(indexes_b) => {
process_group(
*k,
idx_a,
tolerance,
indexes_b,
&mut right_tbl_offsets,
join_asof_fn,
left_asof,
right_asof,
&mut results,
forward,
);
}
// only left values, right = null
None => results.push(None),
}
});
results
})
.flatten()
.collect()
})
}
// TODO! optimize this. This does a full scan backwards. Use the same strategy as in the single `by`
// implementations
fn asof_join_by_multiple<T>(
a: &mut DataFrame,
b: &mut DataFrame,
left_asof: &ChunkedArray<T>,
right_asof: &ChunkedArray<T>,
tolerance: Option<AnyValue<'static>>,
strategy: AsofStrategy,
) -> Vec<Option<IdxSize>>
where
T: PolarsNumericType,
{
#[allow(clippy::type_complexity)]
let (join_asof_fn, tolerance, forward): (
unsafe fn(T::Native, &[T::Native], &[IdxSize], T::Native) -> (Option<IdxSize>, usize),
_,
_,
) = match (tolerance, strategy) {
(Some(tolerance), AsofStrategy::Backward) => {
let tol = tolerance.extract::<T::Native>().unwrap();
(
join_asof_backward_with_indirection_and_tolerance,
tol,
false,
)
}
(None, AsofStrategy::Backward) => (
join_asof_backward_with_indirection,
T::Native::zero(),
false,
),
(Some(tolerance), AsofStrategy::Forward) => {
let tol = tolerance.extract::<T::Native>().unwrap();
(join_asof_forward_with_indirection_and_tolerance, tol, true)
}
(None, AsofStrategy::Forward) => {
(join_asof_forward_with_indirection, T::Native::zero(), true)
}
};
let left_asof = left_asof.rechunk();
let left_asof = left_asof.cont_slice().unwrap();
let right_asof = right_asof.rechunk();
let right_asof = right_asof.cont_slice().unwrap();
let n_threads = POOL.current_num_threads();
let dfs_a = split_df(a, n_threads).unwrap();
let dfs_b = split_df(b, n_threads).unwrap();
let (build_hashes, random_state) = df_rows_to_hashes_threaded(&dfs_b, None).unwrap();
let (probe_hashes, _) = df_rows_to_hashes_threaded(&dfs_a, Some(random_state)).unwrap();
let hash_tbls = mk::create_probe_table(&build_hashes, b);
// early drop to reduce memory pressure
drop(build_hashes);
let n_tables = hash_tbls.len() as u64;
let offsets = mk::get_offsets(&probe_hashes);
// next we probe the other relation
// code duplication is because we want to only do the swap check once
POOL.install(|| {
probe_hashes
.into_par_iter()
.zip(offsets)
.map(|(probe_hashes, offset)| {
// local reference
let hash_tbls = &hash_tbls;
// assume the result tuples equal length of the no. of hashes processed by this thread.
let mut results = Vec::with_capacity(probe_hashes.len());
let mut right_tbl_offsets = PlHashMap::with_capacity(HASHMAP_INIT_SIZE);
let local_offset = offset;
let mut idx_a = local_offset as IdxSize;
for probe_hashes in probe_hashes.data_views() {
for (idx, &h) in probe_hashes.iter().enumerate() {
debug_assert!(idx + offset < left_asof.len());
// probe table that contains the hashed value
let current_probe_table = unsafe {
get_hash_tbl_threaded_join_partitioned(h, hash_tbls, n_tables)
};
let entry = current_probe_table.raw_entry().from_hash(h, |idx_hash| {
let idx_b = idx_hash.idx;
// Safety:
// indices in a join operation are always in bounds.
unsafe { mk::compare_df_rows2(a, b, idx_a as usize, idx_b as usize) }
});
match entry {
// left and right matches
Some((k, indexes_b)) => {
process_group(
// take the first idx as unique identifier of that group.
k.idx,
idx_a,
tolerance,
indexes_b,
&mut right_tbl_offsets,
join_asof_fn,
left_asof,
right_asof,
&mut results,
forward,
);
}
// only left values, right = null
None => results.push(None),
}
idx_a += 1;
}
}
results
})
.flatten()
.collect()
})
}
sourcepub fn data_views(
&self
) -> impl Iterator<Item = &[T::Native]> + DoubleEndedIterator
pub fn data_views(
&self
) -> impl Iterator<Item = &[T::Native]> + DoubleEndedIterator
Get slices of the underlying arrow data. NOTE: null values should be taken into account by the user of these slices as they are handled separately
Examples found in repository?
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
fn as_single_ptr(&mut self) -> PolarsResult<usize> {
let mut ca = self.rechunk();
mem::swap(&mut ca, self);
let a = self.data_views().next().unwrap();
let ptr = a.as_ptr();
Ok(ptr as usize)
}
}
impl AsSinglePtr for BooleanChunked {}
impl AsSinglePtr for ListChunked {}
impl AsSinglePtr for Utf8Chunked {}
#[cfg(feature = "dtype-binary")]
impl AsSinglePtr for BinaryChunked {}
#[cfg(feature = "object")]
impl<T: PolarsObject> AsSinglePtr for ObjectChunked<T> {}
impl<T> ChunkedArray<T>
where
T: PolarsNumericType,
{
/// Contiguous slice
pub fn cont_slice(&self) -> PolarsResult<&[T::Native]> {
if self.chunks.len() == 1 && self.chunks[0].null_count() == 0 {
Ok(self.downcast_iter().next().map(|arr| arr.values()).unwrap())
} else {
Err(PolarsError::ComputeError("cannot take slice".into()))
}
}
/// Get slices of the underlying arrow data.
/// NOTE: null values should be taken into account by the user of these slices as they are handled
/// separately
pub fn data_views(&self) -> impl Iterator<Item = &[T::Native]> + DoubleEndedIterator {
self.downcast_iter().map(|arr| arr.values().as_slice())
}
#[allow(clippy::wrong_self_convention)]
pub fn into_no_null_iter(
&self,
) -> impl Iterator<Item = T::Native>
+ '_
+ Send
+ Sync
+ ExactSizeIterator
+ DoubleEndedIterator
+ TrustedLen {
// .copied was significantly slower in benchmark, next call did not inline?
#[allow(clippy::map_clone)]
// we know the iterators len
unsafe {
self.data_views()
.flatten()
.map(|v| *v)
.trust_my_length(self.len())
}
}
More examples
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
fn apply_cast_numeric<F, S>(&self, f: F) -> ChunkedArray<S>
where
F: Fn(T::Native) -> S::Native + Copy,
S: PolarsNumericType,
{
let chunks = self
.data_views()
.zip(self.iter_validities())
.map(|(slice, validity)| {
let values = Vec::<_>::from_trusted_len_iter(slice.iter().map(|&v| f(v)));
to_array::<S>(values, validity.cloned())
})
.collect();
ChunkedArray::<S>::from_chunks(self.name(), chunks)
}
fn branch_apply_cast_numeric_no_null<F, S>(&self, f: F) -> ChunkedArray<S>
where
F: Fn(Option<T::Native>) -> S::Native,
S: PolarsNumericType,
{
let chunks = self
.downcast_iter()
.map(|array| {
let values = if !array.has_validity() {
let values = array.values().iter().map(|&v| f(Some(v)));
Vec::<_>::from_trusted_len_iter(values)
} else {
let values = array.into_iter().map(|v| f(v.copied()));
Vec::<_>::from_trusted_len_iter(values)
};
to_array::<S>(values, None)
})
.collect();
ChunkedArray::<S>::from_chunks(self.name(), chunks)
}
fn apply<F>(&'a self, f: F) -> Self
where
F: Fn(T::Native) -> T::Native + Copy,
{
let chunks = self
.data_views()
.into_iter()
.zip(self.iter_validities())
.map(|(slice, validity)| {
let values = slice.iter().copied().map(f);
let values = Vec::<_>::from_trusted_len_iter(values);
to_array::<T>(values, validity.cloned())
})
.collect();
ChunkedArray::<T>::from_chunks(self.name(), chunks)
}
fn try_apply<F>(&'a self, f: F) -> PolarsResult<Self>
where
F: Fn(T::Native) -> PolarsResult<T::Native> + Copy,
{
let mut ca: ChunkedArray<T> = self
.data_views()
.into_iter()
.zip(self.iter_validities())
.map(|(slice, validity)| {
let vec: PolarsResult<Vec<_>> = slice.iter().copied().map(f).collect();
Ok((vec?, validity.cloned()))
})
.collect::<PolarsResult<_>>()?;
ca.rename(self.name());
Ok(ca)
}
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
pub(crate) fn create_probe_table(
hashes: &[UInt64Chunked],
keys: &DataFrame,
) -> Vec<HashMap<IdxHash, Vec<IdxSize>, IdBuildHasher>> {
let n_partitions = _set_partition_size();
// We will create a hashtable in every thread.
// We use the hash to partition the keys to the matching hashtable.
// Every thread traverses all keys/hashes and ignores the ones that doesn't fall in that partition.
POOL.install(|| {
(0..n_partitions).into_par_iter().map(|part_no| {
let part_no = part_no as u64;
let mut hash_tbl: HashMap<IdxHash, Vec<IdxSize>, IdBuildHasher> =
HashMap::with_capacity_and_hasher(HASHMAP_INIT_SIZE, Default::default());
let n_partitions = n_partitions as u64;
let mut offset = 0;
for hashes in hashes {
for hashes in hashes.data_views() {
let len = hashes.len();
let mut idx = 0;
hashes.iter().for_each(|h| {
// partition hashes by thread no.
// So only a part of the hashes go to this hashmap
if this_partition(*h, part_no, n_partitions) {
let idx = idx + offset;
populate_multiple_key_hashmap(
&mut hash_tbl,
idx,
*h,
keys,
|| vec![idx],
|v| v.push(idx),
)
}
idx += 1;
});
offset += len as IdxSize;
}
}
hash_tbl
})
})
.collect()
}
fn create_build_table_outer(
hashes: &[UInt64Chunked],
keys: &DataFrame,
) -> Vec<HashMap<IdxHash, (bool, Vec<IdxSize>), IdBuildHasher>> {
// Outer join equivalent of create_build_table() adds a bool in the hashmap values for tracking
// whether a value in the hash table has already been matched to a value in the probe hashes.
let n_partitions = _set_partition_size();
// We will create a hashtable in every thread.
// We use the hash to partition the keys to the matching hashtable.
// Every thread traverses all keys/hashes and ignores the ones that doesn't fall in that partition.
POOL.install(|| {
(0..n_partitions).into_par_iter().map(|part_no| {
let part_no = part_no as u64;
let mut hash_tbl: HashMap<IdxHash, (bool, Vec<IdxSize>), IdBuildHasher> =
HashMap::with_capacity_and_hasher(HASHMAP_INIT_SIZE, Default::default());
let n_partitions = n_partitions as u64;
let mut offset = 0;
for hashes in hashes {
for hashes in hashes.data_views() {
let len = hashes.len();
let mut idx = 0;
hashes.iter().for_each(|h| {
// partition hashes by thread no.
// So only a part of the hashes go to this hashmap
if this_partition(*h, part_no, n_partitions) {
let idx = idx + offset;
populate_multiple_key_hashmap(
&mut hash_tbl,
idx,
*h,
keys,
|| (false, vec![idx]),
|v| v.1.push(idx),
)
}
idx += 1;
});
offset += len as IdxSize;
}
}
hash_tbl
})
})
.collect()
}
/// Probe the build table and add tuples to the results (inner join)
#[allow(clippy::too_many_arguments)]
fn probe_inner<F>(
probe_hashes: &UInt64Chunked,
hash_tbls: &[HashMap<IdxHash, Vec<IdxSize>, IdBuildHasher>],
results: &mut Vec<(IdxSize, IdxSize)>,
local_offset: usize,
n_tables: u64,
a: &DataFrame,
b: &DataFrame,
swap_fn: F,
) where
F: Fn(IdxSize, IdxSize) -> (IdxSize, IdxSize),
{
let mut idx_a = local_offset as IdxSize;
for probe_hashes in probe_hashes.data_views() {
for &h in probe_hashes {
// probe table that contains the hashed value
let current_probe_table =
unsafe { get_hash_tbl_threaded_join_partitioned(h, hash_tbls, n_tables) };
let entry = current_probe_table.raw_entry().from_hash(h, |idx_hash| {
let idx_b = idx_hash.idx;
// Safety:
// indices in a join operation are always in bounds.
unsafe { compare_df_rows2(a, b, idx_a as usize, idx_b as usize) }
});
if let Some((_, indexes_b)) = entry {
let tuples = indexes_b.iter().map(|&idx_b| swap_fn(idx_a, idx_b));
results.extend(tuples);
}
idx_a += 1;
}
}
}
pub(crate) fn get_offsets(probe_hashes: &[UInt64Chunked]) -> Vec<usize> {
probe_hashes
.iter()
.map(|ph| ph.len())
.scan(0, |state, val| {
let out = *state;
*state += val;
Some(out)
})
.collect()
}
pub fn _inner_join_multiple_keys(
a: &mut DataFrame,
b: &mut DataFrame,
swap: bool,
) -> (Vec<IdxSize>, Vec<IdxSize>) {
// we assume that the b DataFrame is the shorter relation.
// b will be used for the build phase.
let n_threads = POOL.current_num_threads();
let dfs_a = split_df(a, n_threads).unwrap();
let dfs_b = split_df(b, n_threads).unwrap();
let (build_hashes, random_state) = df_rows_to_hashes_threaded(&dfs_b, None).unwrap();
let (probe_hashes, _) = df_rows_to_hashes_threaded(&dfs_a, Some(random_state)).unwrap();
let hash_tbls = create_probe_table(&build_hashes, b);
// early drop to reduce memory pressure
drop(build_hashes);
let n_tables = hash_tbls.len() as u64;
let offsets = get_offsets(&probe_hashes);
// next we probe the other relation
// code duplication is because we want to only do the swap check once
POOL.install(|| {
probe_hashes
.into_par_iter()
.zip(offsets)
.map(|(probe_hashes, offset)| {
// local reference
let hash_tbls = &hash_tbls;
let mut results =
Vec::with_capacity(probe_hashes.len() / POOL.current_num_threads());
let local_offset = offset;
// code duplication is to hoist swap out of the inner loop.
if swap {
probe_inner(
&probe_hashes,
hash_tbls,
&mut results,
local_offset,
n_tables,
a,
b,
|idx_a, idx_b| (idx_b, idx_a),
)
} else {
probe_inner(
&probe_hashes,
hash_tbls,
&mut results,
local_offset,
n_tables,
a,
b,
|idx_a, idx_b| (idx_a, idx_b),
)
}
results
})
.flatten()
.unzip()
})
}
#[cfg(feature = "private")]
pub fn private_left_join_multiple_keys(
a: &DataFrame,
b: &DataFrame,
// map the global indices to [chunk_idx, array_idx]
// only needed if we have non contiguous memory
chunk_mapping_left: Option<&[ChunkId]>,
chunk_mapping_right: Option<&[ChunkId]>,
) -> LeftJoinIds {
let mut a = DataFrame::new_no_checks(_to_physical_and_bit_repr(a.get_columns()));
let mut b = DataFrame::new_no_checks(_to_physical_and_bit_repr(b.get_columns()));
_left_join_multiple_keys(&mut a, &mut b, chunk_mapping_left, chunk_mapping_right)
}
pub fn _left_join_multiple_keys(
a: &mut DataFrame,
b: &mut DataFrame,
// map the global indices to [chunk_idx, array_idx]
// only needed if we have non contiguous memory
chunk_mapping_left: Option<&[ChunkId]>,
chunk_mapping_right: Option<&[ChunkId]>,
) -> LeftJoinIds {
// we should not join on logical types
debug_assert!(!a.iter().any(|s| s.dtype().is_logical()));
debug_assert!(!b.iter().any(|s| s.dtype().is_logical()));
let n_threads = POOL.current_num_threads();
let dfs_a = split_df(a, n_threads).unwrap();
let dfs_b = split_df(b, n_threads).unwrap();
let (build_hashes, random_state) = df_rows_to_hashes_threaded(&dfs_b, None).unwrap();
let (probe_hashes, _) = df_rows_to_hashes_threaded(&dfs_a, Some(random_state)).unwrap();
let hash_tbls = create_probe_table(&build_hashes, b);
// early drop to reduce memory pressure
drop(build_hashes);
let n_tables = hash_tbls.len() as u64;
let offsets = get_offsets(&probe_hashes);
// next we probe the other relation
// code duplication is because we want to only do the swap check once
let results = POOL.install(move || {
probe_hashes
.into_par_iter()
.zip(offsets)
.map(move |(probe_hashes, offset)| {
// local reference
let hash_tbls = &hash_tbls;
let len = probe_hashes.len() / POOL.current_num_threads();
let mut result_idx_left = Vec::with_capacity(len);
let mut result_idx_right = Vec::with_capacity(len);
let local_offset = offset;
let mut idx_a = local_offset as IdxSize;
for probe_hashes in probe_hashes.data_views() {
for &h in probe_hashes {
// probe table that contains the hashed value
let current_probe_table = unsafe {
get_hash_tbl_threaded_join_partitioned(h, hash_tbls, n_tables)
};
let entry = current_probe_table.raw_entry().from_hash(h, |idx_hash| {
let idx_b = idx_hash.idx;
// Safety:
// indices in a join operation are always in bounds.
unsafe { compare_df_rows2(a, b, idx_a as usize, idx_b as usize) }
});
match entry {
// left and right matches
Some((_, indexes_b)) => {
result_idx_left
.extend(std::iter::repeat(idx_a).take(indexes_b.len()));
result_idx_right.extend(indexes_b.iter().copied().map(Some))
}
// only left values, right = null
None => {
result_idx_left.push(idx_a);
result_idx_right.push(None);
}
}
idx_a += 1;
}
}
finish_left_join_mappings(
result_idx_left,
result_idx_right,
chunk_mapping_left,
chunk_mapping_right,
)
})
.collect::<Vec<_>>()
});
flatten_left_join_ids(results)
}
#[cfg(feature = "semi_anti_join")]
pub(crate) fn create_build_table_semi_anti(
hashes: &[UInt64Chunked],
keys: &DataFrame,
) -> Vec<HashMap<IdxHash, (), IdBuildHasher>> {
let n_partitions = _set_partition_size();
// We will create a hashtable in every thread.
// We use the hash to partition the keys to the matching hashtable.
// Every thread traverses all keys/hashes and ignores the ones that doesn't fall in that partition.
POOL.install(|| {
(0..n_partitions).into_par_iter().map(|part_no| {
let part_no = part_no as u64;
let mut hash_tbl: HashMap<IdxHash, (), IdBuildHasher> =
HashMap::with_capacity_and_hasher(HASHMAP_INIT_SIZE, Default::default());
let n_partitions = n_partitions as u64;
let mut offset = 0;
for hashes in hashes {
for hashes in hashes.data_views() {
let len = hashes.len();
let mut idx = 0;
hashes.iter().for_each(|h| {
// partition hashes by thread no.
// So only a part of the hashes go to this hashmap
if this_partition(*h, part_no, n_partitions) {
let idx = idx + offset;
populate_multiple_key_hashmap(
&mut hash_tbl,
idx,
*h,
keys,
|| (),
|_| (),
)
}
idx += 1;
});
offset += len as IdxSize;
}
}
hash_tbl
})
})
.collect()
}
#[cfg(feature = "semi_anti_join")]
pub(crate) fn semi_anti_join_multiple_keys_impl<'a>(
a: &'a mut DataFrame,
b: &'a mut DataFrame,
) -> impl ParallelIterator<Item = (IdxSize, bool)> + 'a {
// we should not join on logical types
debug_assert!(!a.iter().any(|s| s.dtype().is_logical()));
debug_assert!(!b.iter().any(|s| s.dtype().is_logical()));
let n_threads = POOL.current_num_threads();
let dfs_a = split_df(a, n_threads).unwrap();
let dfs_b = split_df(b, n_threads).unwrap();
let (build_hashes, random_state) = df_rows_to_hashes_threaded(&dfs_b, None).unwrap();
let (probe_hashes, _) = df_rows_to_hashes_threaded(&dfs_a, Some(random_state)).unwrap();
let hash_tbls = create_build_table_semi_anti(&build_hashes, b);
// early drop to reduce memory pressure
drop(build_hashes);
let n_tables = hash_tbls.len() as u64;
let offsets = get_offsets(&probe_hashes);
// next we probe the other relation
// code duplication is because we want to only do the swap check once
POOL.install(move || {
probe_hashes
.into_par_iter()
.zip(offsets)
.map(move |(probe_hashes, offset)| {
// local reference
let hash_tbls = &hash_tbls;
let mut results =
Vec::with_capacity(probe_hashes.len() / POOL.current_num_threads());
let local_offset = offset;
let mut idx_a = local_offset as IdxSize;
for probe_hashes in probe_hashes.data_views() {
for &h in probe_hashes {
// probe table that contains the hashed value
let current_probe_table = unsafe {
get_hash_tbl_threaded_join_partitioned(h, hash_tbls, n_tables)
};
let entry = current_probe_table.raw_entry().from_hash(h, |idx_hash| {
let idx_b = idx_hash.idx;
// Safety:
// indices in a join operation are always in bounds.
unsafe { compare_df_rows2(a, b, idx_a as usize, idx_b as usize) }
});
match entry {
// left and right matches
Some((_, _)) => results.push((idx_a, true)),
// only left values, right = null
None => results.push((idx_a, false)),
}
idx_a += 1;
}
}
results
})
.flatten()
})
}
#[cfg(feature = "semi_anti_join")]
pub fn _left_anti_multiple_keys(a: &mut DataFrame, b: &mut DataFrame) -> Vec<IdxSize> {
semi_anti_join_multiple_keys_impl(a, b)
.filter(|tpls| !tpls.1)
.map(|tpls| tpls.0)
.collect()
}
#[cfg(feature = "semi_anti_join")]
pub fn _left_semi_multiple_keys(a: &mut DataFrame, b: &mut DataFrame) -> Vec<IdxSize> {
semi_anti_join_multiple_keys_impl(a, b)
.filter(|tpls| tpls.1)
.map(|tpls| tpls.0)
.collect()
}
/// Probe the build table and add tuples to the results (inner join)
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
fn probe_outer<F, G, H>(
probe_hashes: &[UInt64Chunked],
hash_tbls: &mut [HashMap<IdxHash, (bool, Vec<IdxSize>), IdBuildHasher>],
results: &mut Vec<(Option<IdxSize>, Option<IdxSize>)>,
n_tables: u64,
a: &DataFrame,
b: &DataFrame,
// Function that get index_a, index_b when there is a match and pushes to result
swap_fn_match: F,
// Function that get index_a when there is no match and pushes to result
swap_fn_no_match: G,
// Function that get index_b from the build table that did not match any in A and pushes to result
swap_fn_drain: H,
) where
// idx_a, idx_b -> ...
F: Fn(IdxSize, IdxSize) -> (Option<IdxSize>, Option<IdxSize>),
// idx_a -> ...
G: Fn(IdxSize) -> (Option<IdxSize>, Option<IdxSize>),
// idx_b -> ...
H: Fn(IdxSize) -> (Option<IdxSize>, Option<IdxSize>),
{
let mut idx_a = 0;
// vec<ca>
for probe_hashes in probe_hashes {
// ca
for probe_hashes in probe_hashes.data_views() {
// chunk slices
for &h in probe_hashes {
// probe table that contains the hashed value
let current_probe_table =
unsafe { get_hash_tbl_threaded_join_mut_partitioned(h, hash_tbls, n_tables) };
let entry = current_probe_table
.raw_entry_mut()
.from_hash(h, |idx_hash| {
let idx_b = idx_hash.idx;
// Safety:
// indices in a join operation are always in bounds.
unsafe { compare_df_rows2(a, b, idx_a as usize, idx_b as usize) }
});
match entry {
// match and remove
RawEntryMut::Occupied(mut occupied) => {
let (tracker, indexes_b) = occupied.get_mut();
*tracker = true;
results.extend(indexes_b.iter().map(|&idx_b| swap_fn_match(idx_a, idx_b)))
}
// no match
RawEntryMut::Vacant(_) => results.push(swap_fn_no_match(idx_a)),
}
idx_a += 1;
}
}
}
for hash_tbl in hash_tbls {
hash_tbl.iter().for_each(|(_k, (tracker, indexes_b))| {
// remaining unmatched joined values from the right table
if !*tracker {
results.extend(indexes_b.iter().map(|&idx_b| swap_fn_drain(idx_b)))
}
});
}
}
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
pub(crate) fn groupby_threaded_multiple_keys_flat(
mut keys: DataFrame,
n_partitions: usize,
sorted: bool,
) -> PolarsResult<GroupsProxy> {
let dfs = split_df(&mut keys, n_partitions).unwrap();
let (hashes, _random_state) = df_rows_to_hashes_threaded(&dfs, None)?;
let n_partitions = n_partitions as u64;
// trait object to compare inner types.
let keys_cmp = keys
.iter()
.map(|s| s.into_partial_eq_inner())
.collect::<Vec<_>>();
// We will create a hashtable in every thread.
// We use the hash to partition the keys to the matching hashtable.
// Every thread traverses all keys/hashes and ignores the ones that doesn't fall in that partition.
let groups = POOL
.install(|| {
(0..n_partitions).into_par_iter().map(|thread_no| {
let hashes = &hashes;
let mut hash_tbl: HashMap<IdxHash, (IdxSize, Vec<IdxSize>), IdBuildHasher> =
HashMap::with_capacity_and_hasher(HASHMAP_INIT_SIZE, Default::default());
let mut offset = 0;
for hashes in hashes {
let len = hashes.len() as IdxSize;
let mut idx = 0;
for hashes_chunk in hashes.data_views() {
for &h in hashes_chunk {
// partition hashes by thread no.
// So only a part of the hashes go to this hashmap
if this_partition(h, thread_no, n_partitions) {
let idx = idx + offset;
populate_multiple_key_hashmap2(
&mut hash_tbl,
idx,
h,
&keys_cmp,
|| (idx, vec![idx]),
|v| v.1.push(idx),
);
}
idx += 1;
}
}
offset += len;
}
hash_tbl.into_iter().map(|(_k, v)| v).collect::<Vec<_>>()
})
})
.collect::<Vec<_>>();
Ok(finish_group_order(groups, sorted))
}
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
fn asof_join_by_multiple<T>(
a: &mut DataFrame,
b: &mut DataFrame,
left_asof: &ChunkedArray<T>,
right_asof: &ChunkedArray<T>,
tolerance: Option<AnyValue<'static>>,
strategy: AsofStrategy,
) -> Vec<Option<IdxSize>>
where
T: PolarsNumericType,
{
#[allow(clippy::type_complexity)]
let (join_asof_fn, tolerance, forward): (
unsafe fn(T::Native, &[T::Native], &[IdxSize], T::Native) -> (Option<IdxSize>, usize),
_,
_,
) = match (tolerance, strategy) {
(Some(tolerance), AsofStrategy::Backward) => {
let tol = tolerance.extract::<T::Native>().unwrap();
(
join_asof_backward_with_indirection_and_tolerance,
tol,
false,
)
}
(None, AsofStrategy::Backward) => (
join_asof_backward_with_indirection,
T::Native::zero(),
false,
),
(Some(tolerance), AsofStrategy::Forward) => {
let tol = tolerance.extract::<T::Native>().unwrap();
(join_asof_forward_with_indirection_and_tolerance, tol, true)
}
(None, AsofStrategy::Forward) => {
(join_asof_forward_with_indirection, T::Native::zero(), true)
}
};
let left_asof = left_asof.rechunk();
let left_asof = left_asof.cont_slice().unwrap();
let right_asof = right_asof.rechunk();
let right_asof = right_asof.cont_slice().unwrap();
let n_threads = POOL.current_num_threads();
let dfs_a = split_df(a, n_threads).unwrap();
let dfs_b = split_df(b, n_threads).unwrap();
let (build_hashes, random_state) = df_rows_to_hashes_threaded(&dfs_b, None).unwrap();
let (probe_hashes, _) = df_rows_to_hashes_threaded(&dfs_a, Some(random_state)).unwrap();
let hash_tbls = mk::create_probe_table(&build_hashes, b);
// early drop to reduce memory pressure
drop(build_hashes);
let n_tables = hash_tbls.len() as u64;
let offsets = mk::get_offsets(&probe_hashes);
// next we probe the other relation
// code duplication is because we want to only do the swap check once
POOL.install(|| {
probe_hashes
.into_par_iter()
.zip(offsets)
.map(|(probe_hashes, offset)| {
// local reference
let hash_tbls = &hash_tbls;
// assume the result tuples equal length of the no. of hashes processed by this thread.
let mut results = Vec::with_capacity(probe_hashes.len());
let mut right_tbl_offsets = PlHashMap::with_capacity(HASHMAP_INIT_SIZE);
let local_offset = offset;
let mut idx_a = local_offset as IdxSize;
for probe_hashes in probe_hashes.data_views() {
for (idx, &h) in probe_hashes.iter().enumerate() {
debug_assert!(idx + offset < left_asof.len());
// probe table that contains the hashed value
let current_probe_table = unsafe {
get_hash_tbl_threaded_join_partitioned(h, hash_tbls, n_tables)
};
let entry = current_probe_table.raw_entry().from_hash(h, |idx_hash| {
let idx_b = idx_hash.idx;
// Safety:
// indices in a join operation are always in bounds.
unsafe { mk::compare_df_rows2(a, b, idx_a as usize, idx_b as usize) }
});
match entry {
// left and right matches
Some((k, indexes_b)) => {
process_group(
// take the first idx as unique identifier of that group.
k.idx,
idx_a,
tolerance,
indexes_b,
&mut right_tbl_offsets,
join_asof_fn,
left_asof,
right_asof,
&mut results,
forward,
);
}
// only left values, right = null
None => results.push(None),
}
idx_a += 1;
}
}
results
})
.flatten()
.collect()
})
}
sourcepub fn into_no_null_iter(
&self
) -> impl Iterator<Item = T::Native> + '_ + Send + Sync + ExactSizeIterator + DoubleEndedIterator + TrustedLen
pub fn into_no_null_iter(
&self
) -> impl Iterator<Item = T::Native> + '_ + Send + Sync + ExactSizeIterator + DoubleEndedIterator + TrustedLen
Examples found in repository?
More examples
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
fn apply_with_idx<F>(&'a self, f: F) -> Self
where
F: Fn((usize, T::Native)) -> T::Native + Copy,
{
if !self.has_validity() {
let ca: NoNull<_> = self
.into_no_null_iter()
.enumerate()
.map(f)
.collect_trusted();
ca.into_inner()
} else {
// we know that we only iterate over length == self.len()
unsafe {
self.downcast_iter()
.flatten()
.trust_my_length(self.len())
.enumerate()
.map(|(idx, opt_v)| opt_v.map(|v| f((idx, *v))))
.collect_trusted()
}
}
}
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
fn cast(&self, dtype: &DataType) -> PolarsResult<Series> {
match dtype {
DataType::Utf8 => {
let mapping = &**self.get_rev_map();
let mut builder =
Utf8ChunkedBuilder::new(self.logical.name(), self.len(), self.len() * 5);
let f = |idx: u32| mapping.get(idx);
if !self.logical.has_validity() {
self.logical
.into_no_null_iter()
.for_each(|idx| builder.append_value(f(idx)));
} else {
self.logical.into_iter().for_each(|opt_idx| {
builder.append_option(opt_idx.map(f));
});
}
let ca = builder.finish();
Ok(ca.into_series())
}
DataType::UInt32 => {
let ca =
UInt32Chunked::from_chunks(self.logical.name(), self.logical.chunks.clone());
Ok(ca.into_series())
}
#[cfg(feature = "dtype-categorical")]
DataType::Categorical(_) => Ok(self.clone().into_series()),
_ => self.logical.cast(dtype),
}
}
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
fn hash_join_outer(&self, other: &ChunkedArray<T>) -> Vec<(Option<IdxSize>, Option<IdxSize>)> {
let (a, b, swap) = det_hash_prone_order!(self, other);
let n_partitions = _set_partition_size();
let splitted_a = split_ca(a, n_partitions).unwrap();
let splitted_b = split_ca(b, n_partitions).unwrap();
match (a.null_count(), b.null_count()) {
(0, 0) => {
let iters_a = splitted_a
.iter()
.map(|ca| ca.into_no_null_iter())
.collect::<Vec<_>>();
let iters_b = splitted_b
.iter()
.map(|ca| ca.into_no_null_iter())
.collect::<Vec<_>>();
hash_join_tuples_outer(iters_a, iters_b, swap)
}
_ => {
let iters_a = splitted_a
.iter()
.map(|ca| ca.into_iter())
.collect::<Vec<_>>();
let iters_b = splitted_b
.iter()
.map(|ca| ca.into_iter())
.collect::<Vec<_>>();
hash_join_tuples_outer(iters_a, iters_b, swap)
}
}
}
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
fn set_at_idx<I: IntoIterator<Item = IdxSize>>(
&'a self,
idx: I,
value: Option<T::Native>,
) -> PolarsResult<Self> {
if !self.has_validity() {
if let Some(value) = value {
// fast path uses kernel
if self.chunks.len() == 1 {
let arr = set_at_idx_no_null(
self.downcast_iter().next().unwrap(),
idx.into_iter(),
value,
T::get_dtype().to_arrow(),
)?;
return Ok(Self::from_chunks(self.name(), vec![Box::new(arr)]));
}
// Other fast path. Slightly slower as it does not do a memcpy
else {
let mut av = self.into_no_null_iter().collect::<Vec<_>>();
let data = av.as_mut_slice();
idx.into_iter().try_for_each::<_, PolarsResult<_>>(|idx| {
let val = data.get_mut(idx as usize).ok_or_else(|| {
PolarsError::ComputeError(
format!("{} out of bounds on array of length: {}", idx, self.len())
.into(),
)
})?;
*val = value;
Ok(())
})?;
return Ok(Self::from_vec(self.name(), av));
}
}
}
self.set_at_idx_with(idx, |_| value)
}
source§impl ChunkedArray<ListType>
impl ChunkedArray<ListType>
sourcepub fn inner_dtype(&self) -> DataType
pub fn inner_dtype(&self) -> DataType
Get the inner data type of the list.
Examples found in repository?
More examples
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
pub fn par_iter(&self) -> impl ParallelIterator<Item = Option<Series>> + '_ {
self.chunks
.par_iter()
.map(move |arr| {
let dtype = self.inner_dtype();
// Safety:
// guarded by the type system
let arr = &**arr;
let arr = unsafe { &*(arr as *const dyn Array as *const ListArray<i64>) };
(0..arr.len())
.into_par_iter()
.map(move |idx| unsafe { idx_to_array(idx, arr, &dtype) })
})
.flatten()
}
// Get an indexed parallel iterator over the [`Series`] in this [`ListChunked`].
pub fn par_iter_indexed(&mut self) -> impl IndexedParallelIterator<Item = Option<Series>> + '_ {
*self = self.rechunk();
let arr = self.downcast_iter().next().unwrap();
let dtype = self.inner_dtype();
(0..arr.len())
.into_par_iter()
.map(move |idx| unsafe { idx_to_array(idx, arr, &dtype) })
}
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
fn shift_and_fill(&self, periods: i64, fill_value: Option<&Series>) -> ListChunked {
// This has its own implementation because a ListChunked cannot have a full-null without
// knowing the inner type
let periods = clamp(periods, -(self.len() as i64), self.len() as i64);
let slice_offset = (-periods).max(0);
let length = self.len() - abs(periods) as usize;
let mut slice = self.slice(slice_offset, length);
let fill_length = abs(periods) as usize;
let mut fill = match fill_value {
Some(val) => Self::full(self.name(), val, fill_length),
None => {
ListChunked::full_null_with_dtype(self.name(), fill_length, &self.inner_dtype())
}
};
if periods < 0 {
slice.append(&fill).unwrap();
slice
} else {
fill.append(&slice).unwrap();
fill
}
}
sourcepub fn set_inner_dtype(&mut self, dtype: DataType)
pub fn set_inner_dtype(&mut self, dtype: DataType)
Examples found in repository?
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
fn reshape_fast_path(name: &str, s: &Series) -> Series {
let chunks = match s.dtype() {
#[cfg(feature = "dtype-struct")]
DataType::Struct(_) => {
vec![Box::new(array_to_unit_list(s.array_ref(0).clone())) as ArrayRef]
}
_ => s
.chunks()
.iter()
.map(|arr| Box::new(array_to_unit_list(arr.clone())) as ArrayRef)
.collect::<Vec<_>>(),
};
let mut ca = ListChunked::from_chunks(name, chunks);
ca.set_inner_dtype(s.dtype().clone());
ca.set_fast_explode();
ca.into_series()
}
More examples
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
fn cast(&self, data_type: &DataType) -> PolarsResult<Series> {
match data_type {
DataType::List(child_type) => {
let phys_child = child_type.to_physical();
if phys_child.is_primitive() {
let mut ca = if child_type.to_physical() != self.inner_dtype().to_physical() {
let chunks = self
.downcast_iter()
.map(|list| cast_inner_list_type(list, &phys_child))
.collect::<PolarsResult<_>>()?;
ListChunked::from_chunks(self.name(), chunks)
} else {
self.clone()
};
ca.set_inner_dtype(*child_type.clone());
Ok(ca.into_series())
} else {
let ca = self.rechunk();
let arr = ca.downcast_iter().next().unwrap();
let s = Series::try_from(("", arr.values().clone())).unwrap();
let new_inner = s.cast(child_type)?;
let new_values = new_inner.array_ref(0).clone();
let data_type =
ListArray::<i64>::default_datatype(new_values.data_type().clone());
let new_arr = ListArray::<i64>::new(
data_type,
arr.offsets().clone(),
new_values,
arr.validity().cloned(),
);
Series::try_from((self.name(), Box::new(new_arr) as ArrayRef))
}
}
_ => Err(PolarsError::ComputeError("Cannot cast list type".into())),
}
}
source§impl<T: PolarsNumericType> ChunkedArray<T>
impl<T: PolarsNumericType> ChunkedArray<T>
sourcepub fn new_vec(name: &str, v: Vec<T::Native>) -> Self
pub fn new_vec(name: &str, v: Vec<T::Native>) -> Self
Specialization that prevents an allocation
prefer this over ChunkedArray::new when you have a Vec<T::Native>
and no null values.
Examples found in repository?
24 25 26 27 28 29 30 31 32 33 34 35 36 37
fn create_rand_index_no_replacement(
n: usize,
len: usize,
seed: Option<u64>,
shuffle: bool,
) -> IdxCa {
let mut rng = SmallRng::seed_from_u64(seed.unwrap_or_else(get_random_seed));
let mut buf = vec![0; n];
(0..len as IdxSize).choose_multiple_fill(&mut rng, &mut buf);
if shuffle {
buf.shuffle(&mut rng)
}
IdxCa::new_vec("", buf)
}
source§impl<T> ChunkedArray<T>where
T: PolarsNumericType,
ChunkedArray<T>: IntoSeries,
impl<T> ChunkedArray<T>where
T: PolarsNumericType,
ChunkedArray<T>: IntoSeries,
We cannot override the left hand side behaviour. So we create a trait LhsNumOps. This allows for 1.add(&Series)
Trait Implementations§
source§impl<T> Add<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Add<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsNumericType,
source§impl Add<&ChunkedArray<Utf8Type>> for &Utf8Chunked
impl Add<&ChunkedArray<Utf8Type>> for &Utf8Chunked
source§impl<T> Add<ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Add<ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
source§impl Add<ChunkedArray<Utf8Type>> for Utf8Chunked
impl Add<ChunkedArray<Utf8Type>> for Utf8Chunked
source§impl<T, N> Add<N> for &ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
impl<T, N> Add<N> for &ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
source§impl<T, N> Add<N> for ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
impl<T, N> Add<N> for ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
source§impl<T> AggList for ChunkedArray<T>where
T: PolarsNumericType,
ChunkedArray<T>: IntoSeries,
impl<T> AggList for ChunkedArray<T>where
T: PolarsNumericType,
ChunkedArray<T>: IntoSeries,
source§impl<T> ArgAgg for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ArgAgg for ChunkedArray<T>where
T: PolarsNumericType,
source§impl<'a, T> AsMut<ChunkedArray<T>> for dyn SeriesTrait + 'awhere
T: 'static + PolarsDataType,
impl<'a, T> AsMut<ChunkedArray<T>> for dyn SeriesTrait + 'awhere
T: 'static + PolarsDataType,
source§fn as_mut(&mut self) -> &mut ChunkedArray<T>
fn as_mut(&mut self) -> &mut ChunkedArray<T>
source§impl<T: PolarsDataType> AsRef<ChunkedArray<T>> for ChunkedArray<T>
impl<T: PolarsDataType> AsRef<ChunkedArray<T>> for ChunkedArray<T>
source§fn as_ref(&self) -> &ChunkedArray<T>
fn as_ref(&self) -> &ChunkedArray<T>
source§impl<'a, T> AsRef<ChunkedArray<T>> for dyn SeriesTrait + 'awhere
T: 'static + PolarsDataType,
impl<'a, T> AsRef<ChunkedArray<T>> for dyn SeriesTrait + 'awhere
T: 'static + PolarsDataType,
source§fn as_ref(&self) -> &ChunkedArray<T>
fn as_ref(&self) -> &ChunkedArray<T>
source§impl BitAnd<&ChunkedArray<BooleanType>> for &BooleanChunked
impl BitAnd<&ChunkedArray<BooleanType>> for &BooleanChunked
§type Output = ChunkedArray<BooleanType>
type Output = ChunkedArray<BooleanType>
&
operator.source§impl<T> BitAnd<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: BitAnd<Output = T::Native>,
impl<T> BitAnd<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: BitAnd<Output = T::Native>,
source§impl BitAnd<ChunkedArray<BooleanType>> for BooleanChunked
impl BitAnd<ChunkedArray<BooleanType>> for BooleanChunked
§type Output = ChunkedArray<BooleanType>
type Output = ChunkedArray<BooleanType>
&
operator.source§impl BitOr<&ChunkedArray<BooleanType>> for &BooleanChunked
impl BitOr<&ChunkedArray<BooleanType>> for &BooleanChunked
§type Output = ChunkedArray<BooleanType>
type Output = ChunkedArray<BooleanType>
|
operator.source§impl<T> BitOr<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: BitOr<Output = T::Native>,
impl<T> BitOr<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: BitOr<Output = T::Native>,
source§impl BitOr<ChunkedArray<BooleanType>> for BooleanChunked
impl BitOr<ChunkedArray<BooleanType>> for BooleanChunked
§type Output = ChunkedArray<BooleanType>
type Output = ChunkedArray<BooleanType>
|
operator.source§impl BitXor<&ChunkedArray<BooleanType>> for &BooleanChunked
impl BitXor<&ChunkedArray<BooleanType>> for &BooleanChunked
§type Output = ChunkedArray<BooleanType>
type Output = ChunkedArray<BooleanType>
^
operator.source§impl<T> BitXor<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: BitXor<Output = T::Native>,
impl<T> BitXor<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: BitXor<Output = T::Native>,
source§impl BitXor<ChunkedArray<BooleanType>> for BooleanChunked
impl BitXor<ChunkedArray<BooleanType>> for BooleanChunked
§type Output = ChunkedArray<BooleanType>
type Output = ChunkedArray<BooleanType>
^
operator.source§impl<T> ChunkAgg<<T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
impl<T> ChunkAgg<<T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
source§fn sum(&self) -> Option<T::Native>
fn sum(&self) -> Option<T::Native>
None
if the array is empty or only contains null values.fn min(&self) -> Option<T::Native>
source§impl<T> ChunkAggSeries for ChunkedArray<T>where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
ChunkedArray<T>: IntoSeries,
impl<T> ChunkAggSeries for ChunkedArray<T>where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
ChunkedArray<T>: IntoSeries,
source§fn sum_as_series(&self) -> Series
fn sum_as_series(&self) -> Series
source§fn max_as_series(&self) -> Series
fn max_as_series(&self) -> Series
source§fn min_as_series(&self) -> Series
fn min_as_series(&self) -> Series
source§fn prod_as_series(&self) -> Series
fn prod_as_series(&self) -> Series
source§impl<T> ChunkAnyValue for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkAnyValue for ChunkedArray<T>where
T: PolarsNumericType,
source§unsafe fn get_any_value_unchecked(&self, index: usize) -> AnyValue<'_>
unsafe fn get_any_value_unchecked(&self, index: usize) -> AnyValue<'_>
source§fn get_any_value(&self, index: usize) -> PolarsResult<AnyValue<'_>>
fn get_any_value(&self, index: usize) -> PolarsResult<AnyValue<'_>>
source§impl<'a, T> ChunkApply<'a, <T as PolarsNumericType>::Native, <T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
impl<'a, T> ChunkApply<'a, <T as PolarsNumericType>::Native, <T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn apply_cast_numeric<F, S>(&self, f: F) -> ChunkedArray<S>where
F: Fn(T::Native) -> S::Native + Copy,
S: PolarsNumericType,
fn apply_cast_numeric<F, S>(&self, f: F) -> ChunkedArray<S>where
F: Fn(T::Native) -> S::Native + Copy,
S: PolarsNumericType,
source§fn branch_apply_cast_numeric_no_null<F, S>(&self, f: F) -> ChunkedArray<S>where
F: Fn(Option<T::Native>) -> S::Native,
S: PolarsNumericType,
fn branch_apply_cast_numeric_no_null<F, S>(&self, f: F) -> ChunkedArray<S>where
F: Fn(Option<T::Native>) -> S::Native,
S: PolarsNumericType,
source§fn apply<F>(&'a self, f: F) -> Selfwhere
F: Fn(T::Native) -> T::Native + Copy,
fn apply<F>(&'a self, f: F) -> Selfwhere
F: Fn(T::Native) -> T::Native + Copy,
fn try_apply<F>(&'a self, f: F) -> PolarsResult<Self>where
F: Fn(T::Native) -> PolarsResult<T::Native> + Copy,
source§fn apply_on_opt<F>(&'a self, f: F) -> Selfwhere
F: Fn(Option<T::Native>) -> Option<T::Native> + Copy,
fn apply_on_opt<F>(&'a self, f: F) -> Selfwhere
F: Fn(Option<T::Native>) -> Option<T::Native> + Copy,
source§fn apply_with_idx<F>(&'a self, f: F) -> Selfwhere
F: Fn((usize, T::Native)) -> T::Native + Copy,
fn apply_with_idx<F>(&'a self, f: F) -> Selfwhere
F: Fn((usize, T::Native)) -> T::Native + Copy,
source§impl<T> ChunkApplyKernel<PrimitiveArray<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkApplyKernel<PrimitiveArray<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn apply_kernel(
&self,
f: &dyn Fn(&PrimitiveArray<T::Native>) -> ArrayRef
) -> Self
fn apply_kernel(
&self,
f: &dyn Fn(&PrimitiveArray<T::Native>) -> ArrayRef
) -> Self
source§fn apply_kernel_cast<S>(
&self,
f: &dyn Fn(&PrimitiveArray<T::Native>) -> ArrayRef
) -> ChunkedArray<S>where
S: PolarsDataType,
fn apply_kernel_cast<S>(
&self,
f: &dyn Fn(&PrimitiveArray<T::Native>) -> ArrayRef
) -> ChunkedArray<S>where
S: PolarsDataType,
source§impl<T> ChunkCast for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkCast for ChunkedArray<T>where
T: PolarsNumericType,
source§fn cast(&self, data_type: &DataType) -> PolarsResult<Series>
fn cast(&self, data_type: &DataType) -> PolarsResult<Series>
[ChunkedArray]
to [DataType]
source§fn cast_unchecked(&self, data_type: &DataType) -> PolarsResult<Series>
fn cast_unchecked(&self, data_type: &DataType) -> PolarsResult<Series>
source§impl ChunkCompare<&ChunkedArray<BooleanType>> for BooleanChunked
impl ChunkCompare<&ChunkedArray<BooleanType>> for BooleanChunked
type Item = ChunkedArray<BooleanType>
source§fn equal(&self, rhs: &BooleanChunked) -> BooleanChunked
fn equal(&self, rhs: &BooleanChunked) -> BooleanChunked
source§fn not_equal(&self, rhs: &BooleanChunked) -> BooleanChunked
fn not_equal(&self, rhs: &BooleanChunked) -> BooleanChunked
source§fn gt(&self, rhs: &BooleanChunked) -> BooleanChunked
fn gt(&self, rhs: &BooleanChunked) -> BooleanChunked
source§fn gt_eq(&self, rhs: &BooleanChunked) -> BooleanChunked
fn gt_eq(&self, rhs: &BooleanChunked) -> BooleanChunked
source§fn lt(&self, rhs: &BooleanChunked) -> BooleanChunked
fn lt(&self, rhs: &BooleanChunked) -> BooleanChunked
source§fn lt_eq(&self, rhs: &BooleanChunked) -> BooleanChunked
fn lt_eq(&self, rhs: &BooleanChunked) -> BooleanChunked
source§impl ChunkCompare<&ChunkedArray<ListType>> for ListChunked
impl ChunkCompare<&ChunkedArray<ListType>> for ListChunked
type Item = ChunkedArray<BooleanType>
source§fn equal(&self, rhs: &ListChunked) -> BooleanChunked
fn equal(&self, rhs: &ListChunked) -> BooleanChunked
source§fn not_equal(&self, rhs: &ListChunked) -> BooleanChunked
fn not_equal(&self, rhs: &ListChunked) -> BooleanChunked
source§fn gt(&self, _rhs: &ListChunked) -> BooleanChunked
fn gt(&self, _rhs: &ListChunked) -> BooleanChunked
source§fn gt_eq(&self, _rhs: &ListChunked) -> BooleanChunked
fn gt_eq(&self, _rhs: &ListChunked) -> BooleanChunked
source§fn lt(&self, _rhs: &ListChunked) -> BooleanChunked
fn lt(&self, _rhs: &ListChunked) -> BooleanChunked
source§fn lt_eq(&self, _rhs: &ListChunked) -> BooleanChunked
fn lt_eq(&self, _rhs: &ListChunked) -> BooleanChunked
source§impl<T> ChunkCompare<&ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkCompare<&ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
type Item = ChunkedArray<BooleanType>
source§fn equal(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
fn equal(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
source§fn not_equal(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
fn not_equal(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
source§fn gt(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
fn gt(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
source§fn gt_eq(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
fn gt_eq(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
source§fn lt(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
fn lt(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
source§fn lt_eq(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
fn lt_eq(&self, rhs: &ChunkedArray<T>) -> BooleanChunked
source§impl ChunkCompare<&ChunkedArray<Utf8Type>> for Utf8Chunked
impl ChunkCompare<&ChunkedArray<Utf8Type>> for Utf8Chunked
type Item = ChunkedArray<BooleanType>
source§fn equal(&self, rhs: &Utf8Chunked) -> BooleanChunked
fn equal(&self, rhs: &Utf8Chunked) -> BooleanChunked
source§fn not_equal(&self, rhs: &Utf8Chunked) -> BooleanChunked
fn not_equal(&self, rhs: &Utf8Chunked) -> BooleanChunked
source§fn gt(&self, rhs: &Utf8Chunked) -> BooleanChunked
fn gt(&self, rhs: &Utf8Chunked) -> BooleanChunked
source§fn gt_eq(&self, rhs: &Utf8Chunked) -> BooleanChunked
fn gt_eq(&self, rhs: &Utf8Chunked) -> BooleanChunked
source§fn lt(&self, rhs: &Utf8Chunked) -> BooleanChunked
fn lt(&self, rhs: &Utf8Chunked) -> BooleanChunked
source§fn lt_eq(&self, rhs: &Utf8Chunked) -> BooleanChunked
fn lt_eq(&self, rhs: &Utf8Chunked) -> BooleanChunked
source§impl<T, Rhs> ChunkCompare<Rhs> for ChunkedArray<T>where
T: PolarsNumericType,
Rhs: ToPrimitive,
impl<T, Rhs> ChunkCompare<Rhs> for ChunkedArray<T>where
T: PolarsNumericType,
Rhs: ToPrimitive,
type Item = ChunkedArray<BooleanType>
source§fn equal(&self, rhs: Rhs) -> BooleanChunked
fn equal(&self, rhs: Rhs) -> BooleanChunked
source§fn not_equal(&self, rhs: Rhs) -> BooleanChunked
fn not_equal(&self, rhs: Rhs) -> BooleanChunked
source§fn gt(&self, rhs: Rhs) -> BooleanChunked
fn gt(&self, rhs: Rhs) -> BooleanChunked
source§fn gt_eq(&self, rhs: Rhs) -> BooleanChunked
fn gt_eq(&self, rhs: Rhs) -> BooleanChunked
source§fn lt(&self, rhs: Rhs) -> BooleanChunked
fn lt(&self, rhs: Rhs) -> BooleanChunked
source§fn lt_eq(&self, rhs: Rhs) -> BooleanChunked
fn lt_eq(&self, rhs: Rhs) -> BooleanChunked
source§impl<T> ChunkCumAgg<T> for ChunkedArray<T>where
T: PolarsNumericType,
ChunkedArray<T>: FromIterator<Option<T::Native>>,
impl<T> ChunkCumAgg<T> for ChunkedArray<T>where
T: PolarsNumericType,
ChunkedArray<T>: FromIterator<Option<T::Native>>,
source§fn cummax(&self, reverse: bool) -> ChunkedArray<T>
fn cummax(&self, reverse: bool) -> ChunkedArray<T>
source§fn cummin(&self, reverse: bool) -> ChunkedArray<T>
fn cummin(&self, reverse: bool) -> ChunkedArray<T>
source§fn cumsum(&self, reverse: bool) -> ChunkedArray<T>
fn cumsum(&self, reverse: bool) -> ChunkedArray<T>
source§fn cumprod(&self, reverse: bool) -> ChunkedArray<T>
fn cumprod(&self, reverse: bool) -> ChunkedArray<T>
source§impl<T> ChunkExpandAtIndex<T> for ChunkedArray<T>where
ChunkedArray<T>: ChunkFull<T::Native> + TakeRandom<Item = T::Native>,
T: PolarsNumericType + PolarsDataType,
impl<T> ChunkExpandAtIndex<T> for ChunkedArray<T>where
ChunkedArray<T>: ChunkFull<T::Native> + TakeRandom<Item = T::Native>,
T: PolarsNumericType + PolarsDataType,
source§fn new_from_index(&self, index: usize, length: usize) -> ChunkedArray<T>
fn new_from_index(&self, index: usize, length: usize) -> ChunkedArray<T>
source§impl<T> ChunkFillNull for ChunkedArray<T>where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
impl<T> ChunkFillNull for ChunkedArray<T>where
T: PolarsNumericType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
source§fn fill_null(&self, strategy: FillNullStrategy) -> PolarsResult<Self>
fn fill_null(&self, strategy: FillNullStrategy) -> PolarsResult<Self>
source§impl<T> ChunkFillNullValue<<T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkFillNullValue<<T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn fill_null_with_values(&self, value: T::Native) -> PolarsResult<Self>
fn fill_null_with_values(&self, value: T::Native) -> PolarsResult<Self>
T
.source§impl<T> ChunkFilter<T> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkFilter<T> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn filter(&self, filter: &BooleanChunked) -> PolarsResult<ChunkedArray<T>>
fn filter(&self, filter: &BooleanChunked) -> PolarsResult<ChunkedArray<T>>
source§impl<T> ChunkFull<<T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkFull<<T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T> ChunkFullNull for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkFullNull for ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T> ChunkPeaks for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkPeaks for ChunkedArray<T>where
T: PolarsNumericType,
source§fn peak_max(&self) -> BooleanChunked
fn peak_max(&self) -> BooleanChunked
Get a boolean mask of the local maximum peaks.
source§fn peak_min(&self) -> BooleanChunked
fn peak_min(&self) -> BooleanChunked
Get a boolean mask of the local minimum peaks.
source§impl<T> ChunkQuantile<f64> for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
impl<T> ChunkQuantile<f64> for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
source§fn quantile(
&self,
quantile: f64,
interpol: QuantileInterpolOptions
) -> PolarsResult<Option<f64>>
fn quantile(
&self,
quantile: f64,
interpol: QuantileInterpolOptions
) -> PolarsResult<Option<f64>>
None
if the array is empty or only contains null values.source§impl<T> ChunkReverse<T> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkReverse<T> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn reverse(&self) -> ChunkedArray<T>
fn reverse(&self) -> ChunkedArray<T>
source§impl<T> ChunkRollApply for ChunkedArray<T>where
T: PolarsNumericType,
Self: IntoSeries,
impl<T> ChunkRollApply for ChunkedArray<T>where
T: PolarsNumericType,
Self: IntoSeries,
source§fn rolling_apply(
&self,
f: &dyn Fn(&Series) -> Series,
options: RollingOptionsFixedWindow
) -> PolarsResult<Series>
fn rolling_apply(
&self,
f: &dyn Fn(&Series) -> Series,
options: RollingOptionsFixedWindow
) -> PolarsResult<Series>
Apply a rolling custom function. This is pretty slow because of dynamic dispatch.
source§impl<'a, T> ChunkSet<'a, <T as PolarsNumericType>::Native, <T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
impl<'a, T> ChunkSet<'a, <T as PolarsNumericType>::Native, <T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn set_at_idx<I: IntoIterator<Item = IdxSize>>(
&'a self,
idx: I,
value: Option<T::Native>
) -> PolarsResult<Self>
fn set_at_idx<I: IntoIterator<Item = IdxSize>>(
&'a self,
idx: I,
value: Option<T::Native>
) -> PolarsResult<Self>
source§fn set_at_idx_with<I: IntoIterator<Item = IdxSize>, F>(
&'a self,
idx: I,
f: F
) -> PolarsResult<Self>where
F: Fn(Option<T::Native>) -> Option<T::Native>,
fn set_at_idx_with<I: IntoIterator<Item = IdxSize>, F>(
&'a self,
idx: I,
f: F
) -> PolarsResult<Self>where
F: Fn(Option<T::Native>) -> Option<T::Native>,
idx
by applying a closure to these values. Read moresource§fn set(
&'a self,
mask: &BooleanChunked,
value: Option<T::Native>
) -> PolarsResult<Self>
fn set(
&'a self,
mask: &BooleanChunked,
value: Option<T::Native>
) -> PolarsResult<Self>
source§impl<T> ChunkShift<T> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkShift<T> for ChunkedArray<T>where
T: PolarsNumericType,
fn shift(&self, periods: i64) -> ChunkedArray<T>
source§impl<T> ChunkShiftFill<T, Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkShiftFill<T, Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn shift_and_fill(
&self,
periods: i64,
fill_value: Option<T::Native>
) -> ChunkedArray<T>
fn shift_and_fill(
&self,
periods: i64,
fill_value: Option<T::Native>
) -> ChunkedArray<T>
fill_value
.source§impl<T> ChunkSort<T> for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: Default + Ord,
impl<T> ChunkSort<T> for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: Default + Ord,
source§fn argsort_multiple(
&self,
other: &[Series],
reverse: &[bool]
) -> PolarsResult<IdxCa>
fn argsort_multiple(
&self,
other: &[Series],
reverse: &[bool]
) -> PolarsResult<IdxCa>
Panics
This function is very opinionated.
We assume that all numeric Series
are of the same type, if not it will panic
fn sort_with(&self, options: SortOptions) -> ChunkedArray<T>
source§fn sort(&self, reverse: bool) -> ChunkedArray<T>
fn sort(&self, reverse: bool) -> ChunkedArray<T>
ChunkedArray
.source§fn argsort(&self, options: SortOptions) -> IdxCa
fn argsort(&self, options: SortOptions) -> IdxCa
source§impl<T> ChunkTake for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkTake for ChunkedArray<T>where
T: PolarsNumericType,
source§unsafe fn take_unchecked<I, INulls>(
&self,
indices: TakeIdx<'_, I, INulls>
) -> Selfwhere
Self: Sized,
I: TakeIterator,
INulls: TakeIteratorNulls,
unsafe fn take_unchecked<I, INulls>(
&self,
indices: TakeIdx<'_, I, INulls>
) -> Selfwhere
Self: Sized,
I: TakeIterator,
INulls: TakeIteratorNulls,
source§fn take<I, INulls>(&self, indices: TakeIdx<'_, I, INulls>) -> PolarsResult<Self>where
Self: Sized,
I: TakeIterator,
INulls: TakeIteratorNulls,
fn take<I, INulls>(&self, indices: TakeIdx<'_, I, INulls>) -> PolarsResult<Self>where
Self: Sized,
I: TakeIterator,
INulls: TakeIteratorNulls,
source§impl<T> ChunkTakeEvery<T> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkTakeEvery<T> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn take_every(&self, n: usize) -> ChunkedArray<T>
fn take_every(&self, n: usize) -> ChunkedArray<T>
source§impl<T> ChunkUnique<T> for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: Hash + Eq + Ord,
ChunkedArray<T>: IntoSeries,
impl<T> ChunkUnique<T> for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: Hash + Eq + Ord,
ChunkedArray<T>: IntoSeries,
source§fn unique(&self) -> PolarsResult<Self>
fn unique(&self) -> PolarsResult<Self>
source§fn arg_unique(&self) -> PolarsResult<IdxCa>
fn arg_unique(&self) -> PolarsResult<IdxCa>
ChunkedArray
.
This Vec is sorted.source§fn is_unique(&self) -> PolarsResult<BooleanChunked>
fn is_unique(&self) -> PolarsResult<BooleanChunked>
source§fn is_duplicated(&self) -> PolarsResult<BooleanChunked>
fn is_duplicated(&self) -> PolarsResult<BooleanChunked>
source§fn n_unique(&self) -> PolarsResult<usize>
fn n_unique(&self) -> PolarsResult<usize>
ChunkedArray
source§fn mode(&self) -> PolarsResult<Self>
fn mode(&self) -> PolarsResult<Self>
mode
only.source§impl<T> ChunkVar<f64> for ChunkedArray<T>where
T: PolarsIntegerType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
impl<T> ChunkVar<f64> for ChunkedArray<T>where
T: PolarsIntegerType,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
source§impl<T> ChunkZip<T> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> ChunkZip<T> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn zip_with(
&self,
mask: &BooleanChunked,
other: &ChunkedArray<T>
) -> PolarsResult<ChunkedArray<T>>
fn zip_with(
&self,
mask: &BooleanChunked,
other: &ChunkedArray<T>
) -> PolarsResult<ChunkedArray<T>>
true
and values
from other
where the mask evaluates false
source§impl<T: PolarsDataType> Clone for ChunkedArray<T>
impl<T: PolarsDataType> Clone for ChunkedArray<T>
source§impl Debug for ChunkedArray<BooleanType>
impl Debug for ChunkedArray<BooleanType>
source§impl<T> Debug for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Debug for ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T: PolarsDataType> Default for ChunkedArray<T>
impl<T: PolarsDataType> Default for ChunkedArray<T>
source§impl<T> Div<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Div<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T> Div<ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Div<ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T, N> Div<N> for &ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
impl<T, N> Div<N> for &ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
source§impl<T, N> Div<N> for ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
impl<T, N> Div<N> for ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
source§impl<T: PolarsDataType> Drop for ChunkedArray<T>
impl<T: PolarsDataType> Drop for ChunkedArray<T>
source§impl<'a> From<&'a ChunkedArray<BooleanType>> for Vec<Option<bool>>
impl<'a> From<&'a ChunkedArray<BooleanType>> for Vec<Option<bool>>
source§fn from(ca: &'a BooleanChunked) -> Self
fn from(ca: &'a BooleanChunked) -> Self
source§impl<'a, T> From<&'a ChunkedArray<T>> for Vec<Option<T::Native>>where
T: PolarsNumericType,
impl<'a, T> From<&'a ChunkedArray<T>> for Vec<Option<T::Native>>where
T: PolarsNumericType,
source§fn from(ca: &'a ChunkedArray<T>) -> Self
fn from(ca: &'a ChunkedArray<T>) -> Self
source§impl<'a> From<&'a ChunkedArray<UInt32Type>> for TakeIdx<'a, Dummy<usize>, Dummy<Option<usize>>>
impl<'a> From<&'a ChunkedArray<UInt32Type>> for TakeIdx<'a, Dummy<usize>, Dummy<Option<usize>>>
Conversion from UInt32Chunked to Unchecked TakeIdx
source§impl<'a> From<&'a ChunkedArray<Utf8Type>> for Vec<Option<&'a str>>
impl<'a> From<&'a ChunkedArray<Utf8Type>> for Vec<Option<&'a str>>
From trait
source§fn from(ca: &'a Utf8Chunked) -> Self
fn from(ca: &'a Utf8Chunked) -> Self
source§impl<T: PolarsNumericType> From<&[<T as PolarsNumericType>::Native]> for ChunkedArray<T>
impl<T: PolarsNumericType> From<&[<T as PolarsNumericType>::Native]> for ChunkedArray<T>
source§impl<T: PolarsNumericType> From<(&str, PrimitiveArray<<T as PolarsNumericType>::Native>)> for ChunkedArray<T>
impl<T: PolarsNumericType> From<(&str, PrimitiveArray<<T as PolarsNumericType>::Native>)> for ChunkedArray<T>
source§impl From<ChunkedArray<BooleanType>> for Vec<Option<bool>>
impl From<ChunkedArray<BooleanType>> for Vec<Option<bool>>
source§fn from(ca: BooleanChunked) -> Self
fn from(ca: BooleanChunked) -> Self
source§impl<T> From<ChunkedArray<T>> for Serieswhere
T: PolarsDataType,
ChunkedArray<T>: IntoSeries,
impl<T> From<ChunkedArray<T>> for Serieswhere
T: PolarsDataType,
ChunkedArray<T>: IntoSeries,
source§fn from(ca: ChunkedArray<T>) -> Self
fn from(ca: ChunkedArray<T>) -> Self
source§impl From<ChunkedArray<Utf8Type>> for Vec<Option<String>>
impl From<ChunkedArray<Utf8Type>> for Vec<Option<String>>
source§fn from(ca: Utf8Chunked) -> Self
fn from(ca: Utf8Chunked) -> Self
source§impl<T: PolarsNumericType> From<PrimitiveArray<<T as PolarsNumericType>::Native>> for ChunkedArray<T>
impl<T: PolarsNumericType> From<PrimitiveArray<<T as PolarsNumericType>::Native>> for ChunkedArray<T>
source§fn from(a: PrimitiveArray<T::Native>) -> Self
fn from(a: PrimitiveArray<T::Native>) -> Self
source§impl<T> FromIterator<(Vec<<T as PolarsNumericType>::Native, Global>, Option<Bitmap>)> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> FromIterator<(Vec<<T as PolarsNumericType>::Native, Global>, Option<Bitmap>)> for ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T> FromIterator<Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> FromIterator<Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
FromIterator trait
source§impl FromIterator<Option<bool>> for ChunkedArray<BooleanType>
impl FromIterator<Option<bool>> for ChunkedArray<BooleanType>
source§impl<T> FromIteratorReversed<Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> FromIteratorReversed<Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
fn from_trusted_len_iter_rev<I: TrustedLen<Item = Option<T::Native>>>(
iter: I
) -> Self
source§impl<T> FromParallelIterator<Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> FromParallelIterator<Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn from_par_iter<I: IntoParallelIterator<Item = Option<T::Native>>>(
iter: I
) -> Self
fn from_par_iter<I: IntoParallelIterator<Item = Option<T::Native>>>(
iter: I
) -> Self
par_iter
. Read moresource§impl<T> FromTrustedLenIterator<Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> FromTrustedLenIterator<Option<<T as PolarsNumericType>::Native>> for ChunkedArray<T>where
T: PolarsNumericType,
fn from_iter_trusted_length<I: IntoIterator<Item = Option<T::Native>>>(
iter: I
) -> Self
source§impl FromTrustedLenIterator<Option<bool>> for ChunkedArray<BooleanType>
impl FromTrustedLenIterator<Option<bool>> for ChunkedArray<BooleanType>
fn from_iter_trusted_length<I: IntoIterator<Item = Option<bool>>>(
iter: I
) -> Selfwhere
I::IntoIter: TrustedLen,
source§impl<T> IntoGroupsProxy for ChunkedArray<T>where
T: PolarsNumericType,
T::Native: NumCast,
impl<T> IntoGroupsProxy for ChunkedArray<T>where
T: PolarsNumericType,
T::Native: NumCast,
source§fn group_tuples(
&self,
multithreaded: bool,
sorted: bool
) -> PolarsResult<GroupsProxy>
fn group_tuples(
&self,
multithreaded: bool,
sorted: bool
) -> PolarsResult<GroupsProxy>
source§impl<'a, T> IntoIterator for &'a ChunkedArray<T>where
T: PolarsNumericType,
impl<'a, T> IntoIterator for &'a ChunkedArray<T>where
T: PolarsNumericType,
§type Item = Option<<T as PolarsNumericType>::Native>
type Item = Option<<T as PolarsNumericType>::Native>
§type IntoIter = Box<dyn PolarsIterator<Item = <&'a ChunkedArray<T> as IntoIterator>::Item> + 'a, Global>
type IntoIter = Box<dyn PolarsIterator<Item = <&'a ChunkedArray<T> as IntoIterator>::Item> + 'a, Global>
source§impl<T: PolarsDataType + 'static> IntoSeries for ChunkedArray<T>where
SeriesWrap<ChunkedArray<T>>: SeriesTrait,
impl<T: PolarsDataType + 'static> IntoSeries for ChunkedArray<T>where
SeriesWrap<ChunkedArray<T>>: SeriesTrait,
source§impl<'a, T> IntoTakeRandom<'a> for &'a ChunkedArray<T>where
T: PolarsNumericType,
impl<'a, T> IntoTakeRandom<'a> for &'a ChunkedArray<T>where
T: PolarsNumericType,
type Item = <T as PolarsNumericType>::Native
type TakeRandom = TakeRandBranch3<NumTakeRandomCont<'a, <T as PolarsNumericType>::Native>, NumTakeRandomSingleChunk<'a, <T as PolarsNumericType>::Native>, NumTakeRandomChunked<'a, <T as PolarsNumericType>::Native>>
source§fn take_rand(&self) -> Self::TakeRandom
fn take_rand(&self) -> Self::TakeRandom
TakeRandom
.source§impl<T> IsFirst<T> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> IsFirst<T> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn is_first(&self) -> PolarsResult<BooleanChunked>
fn is_first(&self) -> PolarsResult<BooleanChunked>
is_first
only.source§impl<T> IsIn for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> IsIn for ChunkedArray<T>where
T: PolarsNumericType,
source§fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked>
fn is_in(&self, other: &Series) -> PolarsResult<BooleanChunked>
is_in
only.source§impl<T> Mul<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Mul<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T> Mul<ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Mul<ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T, N> Mul<N> for &ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
impl<T, N> Mul<N> for &ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
source§impl<T, N> Mul<N> for ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
impl<T, N> Mul<N> for ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
source§impl NamedFrom<Range<u32>, UInt32Type> for ChunkedArray<UInt32Type>
impl NamedFrom<Range<u32>, UInt32Type> for ChunkedArray<UInt32Type>
source§impl NamedFrom<Range<u64>, UInt64Type> for ChunkedArray<UInt64Type>
impl NamedFrom<Range<u64>, UInt64Type> for ChunkedArray<UInt64Type>
source§impl<T: AsRef<[Option<bool>]>> NamedFrom<T, [Option<bool>]> for ChunkedArray<BooleanType>
impl<T: AsRef<[Option<bool>]>> NamedFrom<T, [Option<bool>]> for ChunkedArray<BooleanType>
source§impl<T: AsRef<[Option<f32>]>> NamedFrom<T, [Option<f32>]> for ChunkedArray<Float32Type>
impl<T: AsRef<[Option<f32>]>> NamedFrom<T, [Option<f32>]> for ChunkedArray<Float32Type>
source§impl<T: AsRef<[Option<f64>]>> NamedFrom<T, [Option<f64>]> for ChunkedArray<Float64Type>
impl<T: AsRef<[Option<f64>]>> NamedFrom<T, [Option<f64>]> for ChunkedArray<Float64Type>
source§impl<T: AsRef<[Option<u32>]>> NamedFrom<T, [Option<u32>]> for ChunkedArray<UInt32Type>
impl<T: AsRef<[Option<u32>]>> NamedFrom<T, [Option<u32>]> for ChunkedArray<UInt32Type>
source§impl<T: AsRef<[Option<u64>]>> NamedFrom<T, [Option<u64>]> for ChunkedArray<UInt64Type>
impl<T: AsRef<[Option<u64>]>> NamedFrom<T, [Option<u64>]> for ChunkedArray<UInt64Type>
source§impl<T: AsRef<[bool]>> NamedFrom<T, [bool]> for ChunkedArray<BooleanType>
impl<T: AsRef<[bool]>> NamedFrom<T, [bool]> for ChunkedArray<BooleanType>
source§impl<T: AsRef<[f32]>> NamedFrom<T, [f32]> for ChunkedArray<Float32Type>
impl<T: AsRef<[f32]>> NamedFrom<T, [f32]> for ChunkedArray<Float32Type>
source§impl<T: AsRef<[f64]>> NamedFrom<T, [f64]> for ChunkedArray<Float64Type>
impl<T: AsRef<[f64]>> NamedFrom<T, [f64]> for ChunkedArray<Float64Type>
source§impl<T: AsRef<[u32]>> NamedFrom<T, [u32]> for ChunkedArray<UInt32Type>
impl<T: AsRef<[u32]>> NamedFrom<T, [u32]> for ChunkedArray<UInt32Type>
source§impl<T: AsRef<[u64]>> NamedFrom<T, [u64]> for ChunkedArray<UInt64Type>
impl<T: AsRef<[u64]>> NamedFrom<T, [u64]> for ChunkedArray<UInt64Type>
source§impl<T> NewChunkedArray<T, <T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> NewChunkedArray<T, <T as PolarsNumericType>::Native> for ChunkedArray<T>where
T: PolarsNumericType,
source§fn from_iter_values(
name: &str,
it: impl Iterator<Item = T::Native>
) -> ChunkedArray<T>
fn from_iter_values(
name: &str,
it: impl Iterator<Item = T::Native>
) -> ChunkedArray<T>
Create a new ChunkedArray from an iterator.
fn from_slice(name: &str, v: &[T::Native]) -> Self
fn from_slice_options(name: &str, opt_v: &[Option<T::Native>]) -> Self
source§fn from_iter_options(
name: &str,
it: impl Iterator<Item = Option<T::Native>>
) -> ChunkedArray<T>
fn from_iter_options(
name: &str,
it: impl Iterator<Item = Option<T::Native>>
) -> ChunkedArray<T>
source§impl<T> NumOpsDispatch for ChunkedArray<T>where
T: PolarsNumericType,
ChunkedArray<T>: IntoSeries,
impl<T> NumOpsDispatch for ChunkedArray<T>where
T: PolarsNumericType,
ChunkedArray<T>: IntoSeries,
fn subtract(&self, rhs: &Series) -> PolarsResult<Series>
fn add_to(&self, rhs: &Series) -> PolarsResult<Series>
fn multiply(&self, rhs: &Series) -> PolarsResult<Series>
fn divide(&self, rhs: &Series) -> PolarsResult<Series>
fn remainder(&self, rhs: &Series) -> PolarsResult<Series>
source§impl<T> NumOpsDispatchChecked for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: CheckedDiv<Output = T::Native> + Zero + One,
ChunkedArray<T>: IntoSeries,
impl<T> NumOpsDispatchChecked for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: CheckedDiv<Output = T::Native> + Zero + One,
ChunkedArray<T>: IntoSeries,
source§fn checked_div(&self, rhs: &Series) -> PolarsResult<Series>
fn checked_div(&self, rhs: &Series) -> PolarsResult<Series>
fn checked_div_num<T: ToPrimitive>(&self, _rhs: T) -> PolarsResult<Series>
source§impl<T> QuantileAggSeries for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
impl<T> QuantileAggSeries for ChunkedArray<T>where
T: PolarsIntegerType,
T::Native: Ord,
<T::Native as Simd>::Simd: Add<Output = <T::Native as Simd>::Simd> + Sum<T::Native> + SimdOrd<T::Native>,
source§fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions
) -> PolarsResult<Series>
fn quantile_as_series(
&self,
quantile: f64,
interpol: QuantileInterpolOptions
) -> PolarsResult<Series>
source§fn median_as_series(&self) -> Series
fn median_as_series(&self) -> Series
source§impl<T> Rem<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Rem<&ChunkedArray<T>> for &ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T> Rem<ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> Rem<ChunkedArray<T>> for ChunkedArray<T>where
T: PolarsNumericType,
source§impl<T, N> Rem<N> for &ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
impl<T, N> Rem<N> for &ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
source§impl<T, N> Rem<N> for ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
impl<T, N> Rem<N> for ChunkedArray<T>where
T: PolarsNumericType,
N: Num + ToPrimitive,
source§impl<T> RepeatBy for ChunkedArray<T>where
T: PolarsNumericType,
impl<T> RepeatBy for ChunkedArray<T>where
T: PolarsNumericType,
source§fn repeat_by(&self, by: &IdxCa) -> ListChunked
fn repeat_by(&self, by: &IdxCa) -> ListChunked
repeat_by
only.n
times, where n
is determined by the values in by
.source§impl<T> StrConcat for ChunkedArray<T>where
T: PolarsNumericType,
T::Native: Display,
impl<T> StrConcat for ChunkedArray<T>where
T: PolarsNumericType,
T::Native: Display,
source§fn str_concat(&self, delimiter: &str) -> Utf8Chunked
fn str_concat(&self, delimiter: &str) -> Utf8Chunked
concat_str
only.