Skip to main content

polars_core/frame/row/
transpose.rs

1use std::borrow::Cow;
2
3use either::Either;
4
5use super::*;
6
7impl DataFrame {
8    pub(crate) fn transpose_from_dtype(
9        &self,
10        dtype: &DataType,
11        keep_names_as: Option<PlSmallStr>,
12        names_out: &[PlSmallStr],
13    ) -> PolarsResult<DataFrame> {
14        let new_width = self.height();
15        let new_height = self.width();
16        // Allocate space for the transposed columns, putting the "row names" first if needed
17        let mut cols_t = match keep_names_as {
18            None => Vec::<Column>::with_capacity(new_width),
19            Some(name) => {
20                let mut tmp = Vec::<Column>::with_capacity(new_width + 1);
21                tmp.push(
22                    StringChunked::from_iter_values(
23                        name,
24                        self.get_column_names_owned().into_iter(),
25                    )
26                    .into_column(),
27                );
28                tmp
29            },
30        };
31
32        let cols = self.columns();
33        match dtype {
34            #[cfg(feature = "dtype-i8")]
35            DataType::Int8 => numeric_transpose::<Int8Type>(cols, names_out, &mut cols_t),
36            #[cfg(feature = "dtype-i16")]
37            DataType::Int16 => numeric_transpose::<Int16Type>(cols, names_out, &mut cols_t),
38            DataType::Int32 => numeric_transpose::<Int32Type>(cols, names_out, &mut cols_t),
39            DataType::Int64 => numeric_transpose::<Int64Type>(cols, names_out, &mut cols_t),
40            #[cfg(feature = "dtype-u8")]
41            DataType::UInt8 => numeric_transpose::<UInt8Type>(cols, names_out, &mut cols_t),
42            #[cfg(feature = "dtype-u16")]
43            DataType::UInt16 => numeric_transpose::<UInt16Type>(cols, names_out, &mut cols_t),
44            DataType::UInt32 => numeric_transpose::<UInt32Type>(cols, names_out, &mut cols_t),
45            DataType::UInt64 => numeric_transpose::<UInt64Type>(cols, names_out, &mut cols_t),
46            DataType::Float32 => numeric_transpose::<Float32Type>(cols, names_out, &mut cols_t),
47            DataType::Float64 => numeric_transpose::<Float64Type>(cols, names_out, &mut cols_t),
48            #[cfg(feature = "object")]
49            DataType::Object(_) => {
50                // this requires to support `Object` in Series::iter which we don't yet
51                polars_bail!(InvalidOperation: "Object dtype not supported in 'transpose'")
52            },
53            _ => {
54                let phys_dtype = dtype.to_physical();
55                let mut buffers = (0..new_width)
56                    .map(|_| {
57                        let buf: AnyValueBufferTrusted = (&phys_dtype, new_height).into();
58                        buf
59                    })
60                    .collect::<Vec<_>>();
61
62                let columns = self
63                    .materialized_column_iter()
64                    // first cast to supertype before casting to physical to ensure units are correct
65                    .map(|s| Ok(s.cast(dtype)?.to_physical_repr().into_owned()))
66                    .collect::<PolarsResult<Vec<_>>>()?;
67
68                // this is very expensive. A lot of cache misses here.
69                // This is the part that is performance critical.
70                for series in &columns {
71                    polars_ensure!(
72                        series.dtype() == &phys_dtype,
73                        ComputeError: "cannot transpose with supertype: {}", dtype
74                    );
75                    for (av, buf) in series.iter().zip(buffers.iter_mut()) {
76                        // SAFETY: we checked the type and we borrow
77                        unsafe {
78                            buf.add_unchecked_borrowed_physical(&av);
79                        }
80                    }
81                }
82                cols_t.extend(buffers.into_iter().zip(names_out).map(|(buf, name)| {
83                    // SAFETY: we are casting back to the supertype
84                    let mut s = unsafe { buf.into_series().cast_unchecked(dtype).unwrap() };
85                    s.rename(name.clone());
86                    s.into()
87                }));
88            },
89        };
90
91        DataFrame::new(new_height, cols_t)
92    }
93
94    pub fn transpose(
95        &mut self,
96        keep_names_as: Option<&str>,
97        new_col_names: Option<Either<String, Vec<String>>>,
98    ) -> PolarsResult<DataFrame> {
99        let new_col_names = match new_col_names {
100            None => None,
101            Some(Either::Left(v)) => Some(Either::Left(v.into())),
102            Some(Either::Right(v)) => Some(Either::Right(
103                v.into_iter().map(Into::into).collect::<Vec<_>>(),
104            )),
105        };
106
107        self.transpose_impl(keep_names_as, new_col_names)
108    }
109    /// Transpose a DataFrame. This is a very expensive operation.
110    pub fn transpose_impl(
111        &mut self,
112        keep_names_as: Option<&str>,
113        new_col_names: Option<Either<PlSmallStr, Vec<PlSmallStr>>>,
114    ) -> PolarsResult<DataFrame> {
115        // We must iterate columns as [`AnyValue`], so we must be contiguous.
116        self.rechunk_mut_par();
117
118        let mut df = Cow::Borrowed(self); // Can't use self because we might drop a name column
119        let names_out = match new_col_names {
120            None => (0..self.height())
121                .map(|i| format_pl_smallstr!("column_{i}"))
122                .collect(),
123            Some(cn) => match cn {
124                Either::Left(name) => {
125                    let new_names = self.column(name.as_str()).and_then(|x| x.str())?;
126                    polars_ensure!(new_names.null_count() == 0, ComputeError: "Column with new names can't have null values");
127                    df = Cow::Owned(self.drop(name.as_str())?);
128                    new_names.no_null_iter().map(PlSmallStr::from_str).collect()
129                },
130                Either::Right(names) => {
131                    polars_ensure!(names.len() == self.height(), ShapeMismatch: "Length of new column names must be the same as the row count");
132                    names
133                },
134            },
135        };
136        if let Some(cn) = keep_names_as {
137            // Check that the column name we're using for the original column names is unique before
138            // wasting time transposing
139            polars_ensure!(names_out.iter().all(|a| a.as_str() != cn), Duplicate: "{} is already in output column names", cn)
140        }
141        let dtype = df.get_supertype().unwrap_or(Ok(DataType::Null))?;
142        df.transpose_from_dtype(&dtype, keep_names_as.map(PlSmallStr::from_str), &names_out)
143    }
144}
145
146#[inline]
147unsafe fn add_value<T: NumericNative>(
148    values_buf_ptr: usize,
149    col_idx: usize,
150    row_idx: usize,
151    value: T,
152) {
153    let vec_ref: &mut Vec<Vec<T>> = &mut *(values_buf_ptr as *mut Vec<Vec<T>>);
154    let column = vec_ref.get_unchecked_mut(col_idx);
155    let el_ptr = column.as_mut_ptr();
156    *el_ptr.add(row_idx) = value;
157}
158
159// This just fills a pre-allocated mutable series vector, which may have a name column.
160// Nothing is returned and the actual DataFrame is constructed above.
161pub(super) fn numeric_transpose<T: PolarsNumericType>(
162    cols: &[Column],
163    names_out: &[PlSmallStr],
164    cols_t: &mut Vec<Column>,
165) {
166    let new_width = cols[0].len();
167    let new_height = cols.len();
168
169    let has_nulls = cols.iter().any(|s| s.null_count() > 0);
170
171    let mut values_buf: Vec<Vec<T::Native>> = (0..new_width)
172        .map(|_| Vec::with_capacity(new_height))
173        .collect();
174    let mut validity_buf: Vec<_> = if has_nulls {
175        // we first use bools instead of bits, because we can access these in parallel without aliasing
176        (0..new_width).map(|_| vec![true; new_height]).collect()
177    } else {
178        (0..new_width).map(|_| vec![]).collect()
179    };
180
181    // work with *mut pointers because we it is UB write to &refs.
182    let values_buf_ptr = &mut values_buf as *mut Vec<Vec<T::Native>> as usize;
183    let validity_buf_ptr = &mut validity_buf as *mut Vec<Vec<bool>> as usize;
184
185    RAYON.install(|| {
186        cols.iter()
187            .map(Column::as_materialized_series)
188            .enumerate()
189            .for_each(|(row_idx, s)| {
190                let s = s.cast(&T::get_static_dtype()).unwrap();
191                let ca = s.unpack::<T>().unwrap();
192
193                // SAFETY:
194                // we access in parallel, but every access is unique, so we don't break aliasing rules
195                // we also ensured we allocated enough memory, so we never reallocate and thus
196                // the pointers remain valid.
197                if has_nulls {
198                    for (col_idx, opt_v) in ca.iter().enumerate() {
199                        match opt_v {
200                            None => unsafe {
201                                let validity_vec: &mut Vec<Vec<bool>> =
202                                    &mut *(validity_buf_ptr as *mut Vec<Vec<bool>>);
203                                let column = validity_vec.get_unchecked_mut(col_idx);
204                                let el_ptr = column.as_mut_ptr();
205                                *el_ptr.add(row_idx) = false;
206                                // we must initialize this memory otherwise downstream code
207                                // might access uninitialized memory when the masked out values
208                                // are changed.
209                                add_value(values_buf_ptr, col_idx, row_idx, T::Native::default());
210                            },
211                            Some(v) => unsafe {
212                                add_value(values_buf_ptr, col_idx, row_idx, v);
213                            },
214                        }
215                    }
216                } else {
217                    for (col_idx, v) in ca.into_no_null_iter().enumerate() {
218                        unsafe {
219                            let column: &mut Vec<Vec<T::Native>> =
220                                &mut *(values_buf_ptr as *mut Vec<Vec<T::Native>>);
221                            let el_ptr = column.get_unchecked_mut(col_idx).as_mut_ptr();
222                            *el_ptr.add(row_idx) = v;
223                        }
224                    }
225                }
226            })
227    });
228
229    let par_iter = values_buf
230        .into_par_iter()
231        .zip(validity_buf)
232        .zip(names_out)
233        .map(|((mut values, validity), name)| {
234            // SAFETY:
235            // all values are written we can now set len
236            unsafe {
237                values.set_len(new_height);
238            }
239
240            let validity = if has_nulls {
241                let validity = Bitmap::from_trusted_len_iter(validity.iter().copied());
242                if validity.unset_bits() > 0 {
243                    Some(validity)
244                } else {
245                    None
246                }
247            } else {
248                None
249            };
250
251            let arr = PrimitiveArray::<T::Native>::new(
252                T::get_static_dtype().to_arrow(CompatLevel::newest()),
253                values.into(),
254                validity,
255            );
256            ChunkedArray::<T>::with_chunk(name.clone(), arr).into_column()
257        });
258    RAYON.install(|| cols_t.par_extend(par_iter));
259}
260
261#[cfg(test)]
262mod test {
263    use super::*;
264
265    #[test]
266    fn test_transpose() -> PolarsResult<()> {
267        let mut df = df![
268            "a" => [1, 2, 3],
269            "b" => [10, 20, 30],
270        ]?;
271
272        let out = df.transpose(None, None)?;
273        let expected = df![
274            "column_0" => [1, 10],
275            "column_1" => [2, 20],
276            "column_2" => [3, 30],
277
278        ]?;
279        assert!(out.equals_missing(&expected));
280
281        let mut df = df![
282            "a" => [Some(1), None, Some(3)],
283            "b" => [Some(10), Some(20), None],
284        ]?;
285        let out = df.transpose(None, None)?;
286        let expected = df![
287            "column_0" => [1, 10],
288            "column_1" => [None, Some(20)],
289            "column_2" => [Some(3), None],
290
291        ]?;
292        assert!(out.equals_missing(&expected));
293
294        let mut df = df![
295            "a" => ["a", "b", "c"],
296            "b" => [Some(10), Some(20), None],
297        ]?;
298        let out = df.transpose(None, None)?;
299        let expected = df![
300            "column_0" => ["a", "10"],
301            "column_1" => ["b", "20"],
302            "column_2" => [Some("c"), None],
303
304        ]?;
305        assert!(out.equals_missing(&expected));
306        Ok(())
307    }
308}