1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
mod asof;
mod groups;
use crate::prelude::*;
use asof::*;
use num::Bounded;
use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq)]
pub struct AsOfOptions {
pub strategy: AsofStrategy,
pub tolerance: Option<AnyValue<'static>>,
pub tolerance_str: Option<String>,
pub left_by: Option<Vec<String>>,
pub right_by: Option<Vec<String>>,
}
fn check_asof_columns(a: &Series, b: &Series) -> Result<()> {
if a.dtype() != b.dtype() {
return Err(PolarsError::ComputeError(
format!(
"keys used in asof-join must have equal dtypes. We got: left: {:?}\tright: {:?}",
a.dtype(),
b.dtype()
)
.into(),
));
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AsofStrategy {
Backward,
Forward,
}
impl<T> ChunkedArray<T>
where
T: PolarsNumericType,
T::Native: Bounded + PartialOrd,
{
pub(crate) fn join_asof(
&self,
other: &Series,
strategy: AsofStrategy,
tolerance: Option<AnyValue<'static>>,
) -> Result<Vec<Option<IdxSize>>> {
let other = self.unpack_series_matching_type(other)?;
if self.null_count() > 0 || other.null_count() > 0 {
return Err(PolarsError::ComputeError(
"asof join must not have null values in 'on' arguments".into(),
));
}
let out = match strategy {
AsofStrategy::Forward => match tolerance {
None => join_asof_forward(self.cont_slice().unwrap(), other.cont_slice().unwrap()),
Some(tolerance) => {
let tolerance = tolerance.extract::<T::Native>().unwrap();
join_asof_forward_with_tolerance(
self.cont_slice().unwrap(),
other.cont_slice().unwrap(),
tolerance,
)
}
},
AsofStrategy::Backward => match tolerance {
None => join_asof_backward(self.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)
}
}
impl DataFrame {
#[cfg_attr(docsrs, doc(cfg(feature = "asof_join")))]
pub fn join_asof(
&self,
other: &DataFrame,
left_on: &str,
right_on: &str,
strategy: AsofStrategy,
tolerance: Option<AnyValue<'static>>,
suffix: Option<String>,
) -> Result<DataFrame> {
let left_key = self.column(left_on)?;
let right_key = other.column(right_on)?;
check_asof_columns(left_key, right_key)?;
let left_key = left_key.to_physical_repr();
let right_key = right_key.to_physical_repr();
let take_idx = match left_key.dtype() {
DataType::Int64 => left_key
.i64()
.unwrap()
.join_asof(&right_key, strategy, tolerance),
DataType::Int32 => left_key
.i32()
.unwrap()
.join_asof(&right_key, strategy, tolerance),
DataType::UInt64 => left_key
.u64()
.unwrap()
.join_asof(&right_key, strategy, tolerance),
DataType::UInt32 => left_key
.u32()
.unwrap()
.join_asof(&right_key, strategy, tolerance),
_ => {
let left_key = left_key.cast(&DataType::Int32).unwrap();
let right_key = right_key.cast(&DataType::Int32).unwrap();
left_key
.i32()
.unwrap()
.join_asof(&right_key, strategy, tolerance)
}
}?;
if let Some(Some(idx)) = take_idx.last() {
assert!((*idx as usize) < other.height())
}
let other = if left_on == right_on {
Cow::Owned(other.drop(right_on)?)
} else {
Cow::Borrowed(other)
};
let right_df = unsafe {
other.take_opt_iter_unchecked(
take_idx
.into_iter()
.map(|opt_idx| opt_idx.map(|idx| idx as usize)),
)
};
self.finish_join(self.clone(), right_df, suffix)
}
}