Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-core/src/frame/column/arithmetic.rs
8446 views
1
use num_traits::{Num, NumCast};
2
use polars_error::PolarsResult;
3
4
use super::{Column, ScalarColumn, Series};
5
6
fn num_op_with_broadcast<T: Num + NumCast, F: Fn(&Series, T) -> Series>(
7
c: &'_ Column,
8
n: T,
9
op: F,
10
) -> Column {
11
match c {
12
Column::Series(s) => op(s, n).into(),
13
Column::Scalar(s) => {
14
ScalarColumn::from_single_value_series(op(&s.as_single_value_series(), n), s.len())
15
.into()
16
},
17
}
18
}
19
20
macro_rules! broadcastable_ops {
21
($(($trait:ident, $op:ident))+) => {
22
$(
23
impl std::ops::$trait for Column {
24
type Output = PolarsResult<Column>;
25
26
#[inline]
27
fn $op(self, rhs: Self) -> Self::Output {
28
self.try_apply_broadcasting_binary_elementwise(&rhs, |l, r| l.$op(r))
29
}
30
}
31
32
impl std::ops::$trait for &Column {
33
type Output = PolarsResult<Column>;
34
35
#[inline]
36
fn $op(self, rhs: Self) -> Self::Output {
37
self.try_apply_broadcasting_binary_elementwise(rhs, |l, r| l.$op(r))
38
}
39
}
40
)+
41
}
42
}
43
44
macro_rules! broadcastable_num_ops {
45
($(($trait:ident, $op:ident))+) => {
46
$(
47
impl<T> std::ops::$trait::<T> for Column
48
where
49
T: Num + NumCast,
50
{
51
type Output = Self;
52
53
#[inline]
54
fn $op(self, rhs: T) -> Self::Output {
55
num_op_with_broadcast(&self, rhs, |l, r| l.$op(r))
56
}
57
}
58
59
impl<T> std::ops::$trait::<T> for &Column
60
where
61
T: Num + NumCast,
62
{
63
type Output = Column;
64
65
#[inline]
66
fn $op(self, rhs: T) -> Self::Output {
67
num_op_with_broadcast(self, rhs, |l, r| l.$op(r))
68
}
69
}
70
)+
71
};
72
}
73
74
broadcastable_ops! {
75
(Add, add)
76
(Sub, sub)
77
(Mul, mul)
78
(Div, div)
79
(Rem, rem)
80
(BitAnd, bitand)
81
(BitOr, bitor)
82
(BitXor, bitxor)
83
}
84
85
broadcastable_num_ops! {
86
(Add, add)
87
(Sub, sub)
88
(Mul, mul)
89
(Div, div)
90
(Rem, rem)
91
}
92
93