polars_core/frame/
horizontal.rs1use polars_error::{PolarsResult, polars_err};
2
3use super::Column;
4use crate::datatypes::AnyValue;
5use crate::frame::DataFrame;
6use crate::frame::validation::validate_columns_slice;
7
8impl DataFrame {
9 pub unsafe fn hstack_mut_unchecked(&mut self, columns: &[Column]) -> &mut Self {
21 if self.shape() == (0, 0)
22 && let Some(c) = columns.first()
23 {
24 unsafe { self.set_height(c.len()) };
25 }
26
27 unsafe { self.columns_mut() }.extend_from_slice(columns);
28
29 if cfg!(debug_assertions) {
30 if let err @ Err(_) = validate_columns_slice(self.height(), self.columns()) {
31 let initial_width = self.width() - columns.len();
32 unsafe { self.columns_mut() }.truncate(initial_width);
33 err.unwrap();
34 }
35 }
36
37 self
38 }
39
40 pub fn hstack_mut(&mut self, columns: &[Column]) -> PolarsResult<&mut Self> {
55 if self.shape() == (0, 0)
56 && let Some(c) = columns.first()
57 {
58 unsafe { self.set_height(c.len()) };
59 }
60
61 unsafe { self.columns_mut() }.extend_from_slice(columns);
62
63 if let err @ Err(_) = validate_columns_slice(self.height(), self.columns()) {
64 let initial_width = self.width() - columns.len();
65 unsafe { self.columns_mut() }.truncate(initial_width);
66 err?;
67 }
68
69 Ok(self)
70 }
71}
72
73pub fn concat_df_horizontal(
77 dfs: &[DataFrame],
78 check_duplicates: bool,
79 strict: bool,
80 unit_length_as_scalar: bool,
81) -> PolarsResult<DataFrame> {
82 if dfs.is_empty() {
83 return Err(polars_err!(ComputeError: "cannot concat empty dataframes"));
84 }
85 let heights = || dfs.iter().map(|df| df.height());
86 let output_height = if unit_length_as_scalar {
87 heights().filter(|h| *h != 1).max().unwrap_or(1)
88 } else {
89 heights().max().unwrap()
90 };
91
92 let owned_df;
93
94 let mut out_width = 0;
95
96 let all_equal_height = dfs.iter().filter(|df| df.shape() != (0, 0)).all(|df| {
97 out_width += df.width();
98 df.height() == output_height
99 });
100
101 let dfs = if !all_equal_height {
103 if strict {
104 return Err(
105 polars_err!(ShapeMismatch: "cannot concat dataframes with different heights in 'strict' mode"),
106 );
107 }
108 out_width = 0;
109
110 owned_df = dfs
111 .iter()
112 .filter(|df| df.shape() != (0, 0))
113 .cloned()
114 .map(|mut df| {
115 out_width += df.width();
116 let h = df.height();
117
118 if h != output_height {
119 if unit_length_as_scalar && h == 1 {
120 unsafe { df.columns_mut() }.iter_mut().for_each(|c| {
123 *c = c.new_from_index(0, output_height);
124 });
125 } else {
126 let diff = output_height - h;
127
128 unsafe { df.columns_mut() }.iter_mut().for_each(|c| {
131 *c = c.extend_constant(AnyValue::Null, diff).unwrap();
132 });
133 }
134 unsafe {
135 df.set_height(output_height);
136 }
137 }
138
139 df
140 })
141 .collect::<Vec<_>>();
142 owned_df.as_slice()
143 } else {
144 dfs
145 };
146
147 let mut acc_cols = Vec::with_capacity(out_width);
148
149 for df in dfs {
150 acc_cols.extend(df.columns().iter().cloned());
151 }
152
153 let df = if check_duplicates {
154 DataFrame::new(output_height, acc_cols)?
155 } else {
156 unsafe { DataFrame::new_unchecked(output_height, acc_cols) }
157 };
158
159 Ok(df)
160}
161
162#[cfg(test)]
163mod tests {
164 use polars_error::PolarsError;
165
166 #[test]
167 fn test_hstack_mut_empty_frame_height_validation() {
168 use crate::frame::DataFrame;
169 use crate::prelude::{Column, DataType};
170 let mut df = DataFrame::empty();
171 let result = df.hstack_mut(&[
172 Column::full_null("a".into(), 1, &DataType::Null),
173 Column::full_null("b".into(), 3, &DataType::Null),
174 ]);
175
176 assert!(
177 matches!(result, Err(PolarsError::ShapeMismatch(_))),
178 "expected shape mismatch error"
179 );
180 assert_eq!(df.width(), 0);
182 }
183
184 #[test]
185 fn test_scalar_broadcast_over_empty_frame() {
186 use crate::prelude::*;
187
188 let empty = df!["a" => Vec::<i64>::new()].unwrap();
190 let scalar = df!["b" => [1i64]].unwrap();
191 let out = super::concat_df_horizontal(&[empty, scalar], true, false, true).unwrap();
192 assert_eq!(out.height(), 0);
193 assert_eq!(out.width(), 2);
194
195 let non_empty = df!["a" => [10i64, 20, 30]].unwrap();
197 let scalar = df!["b" => [1i64]].unwrap();
198 let out = super::concat_df_horizontal(&[non_empty, scalar], true, false, true).unwrap();
199 assert_eq!(out.height(), 3);
200 assert_eq!(
201 out.column("b").unwrap().as_materialized_series(),
202 &Series::new("b".into(), [1i64, 1, 1])
203 );
204 }
205}