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
use crate::prelude::*;
use ndarray::prelude::*;
impl<T> ChunkedArray<T>
where
T: PolarsNumericType,
{
#[cfg_attr(docsrs, doc(cfg(feature = "ndarray")))]
pub fn to_ndarray(&self) -> Result<ArrayView1<T::Native>> {
let slice = self.cont_slice()?;
Ok(aview1(slice))
}
}
impl ListChunked {
#[cfg_attr(docsrs, doc(cfg(feature = "ndarray")))]
pub fn to_ndarray<N>(&self) -> Result<Array2<N::Native>>
where
N: PolarsNumericType,
{
if self.null_count() != 0 {
Err(PolarsError::HasNullValues(
"Creation of ndarray with null values is not supported.".into(),
))
} else {
let mut iter = self.into_no_null_iter();
let mut ndarray;
let width;
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());
unsafe { Ok(ndarray.assume_init()) }
} else {
Err(PolarsError::NoData(
"cannot create ndarray of empty ListChunked".into(),
))
}
}
}
}
impl DataFrame {
#[cfg_attr(docsrs, doc(cfg(feature = "ndarray")))]
pub fn to_ndarray<N>(&self) -> Result<Array2<N::Native>>
where
N: PolarsNumericType,
{
let mut ndarr = Array2::zeros(self.shape());
for (col_idx, series) in self.get_columns().iter().enumerate() {
if series.null_count() != 0 {
return Err(PolarsError::HasNullValues(
"Creation of ndarray with null values is not supported.".into(),
));
}
let series = series.cast(&N::get_dtype())?;
let ca = series.unpack::<N>()?;
ca.into_no_null_iter()
.enumerate()
.for_each(|(row_idx, val)| {
ndarr[[row_idx, col_idx]] = val;
})
}
Ok(ndarr)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_ndarray_from_ca() -> Result<()> {
let ca = Float64Chunked::new_from_slice("", &[1.0, 2.0, 3.0]);
let ndarr = ca.to_ndarray()?;
assert_eq!(ndarr, ArrayView1::from(&[1.0, 2.0, 3.0]));
let mut builder = ListPrimitiveChunkedBuilder::new("", 10, 10, DataType::Float64);
builder.append_slice(Some(&[1.0, 2.0, 3.0]));
builder.append_slice(Some(&[2.0, 4.0, 5.0]));
builder.append_slice(Some(&[6.0, 7.0, 8.0]));
let list = builder.finish();
let ndarr = list.to_ndarray::<Float64Type>()?;
let expected = array![[1.0, 2.0, 3.0], [2.0, 4.0, 5.0], [6.0, 7.0, 8.0]];
assert_eq!(ndarr, expected);
let mut builder = ListPrimitiveChunkedBuilder::new("", 10, 10, DataType::Float64);
builder.append_slice(Some(&[1.0, 2.0, 3.0]));
builder.append_slice(Some(&[2.0]));
builder.append_slice(Some(&[6.0, 7.0, 8.0]));
let list = builder.finish();
assert!(list.to_ndarray::<Float64Type>().is_err());
Ok(())
}
#[test]
fn test_ndarray_from_df() -> Result<()> {
let df = df!["a"=> [1.0, 2.0, 3.0],
"b" => [2.0, 3.0, 4.0]
]?;
let ndarr = df.to_ndarray::<Float64Type>()?;
let expected = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
assert_eq!(ndarr, expected);
Ok(())
}
}