Skip to content

Commit

Permalink
handle empty arrays when inferring schema (#297)
Browse files Browse the repository at this point in the history
Co-authored-by: Thomas McKenna <[email protected]>
  • Loading branch information
tmckenn2 and Thomas McKenna authored Nov 26, 2024
1 parent d806f3c commit 9ae34f8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
10 changes: 10 additions & 0 deletions __tests__/dataframe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2008,6 +2008,16 @@ describe("create", () => {
string: pl.String,
});
});
test("from row objects, inferred schema, empty array", () => {
const df = pl.readRecords([
{ a: [], b: 0 },
{ a: [""], b: 0 },
]);
expect(df.schema).toStrictEqual({
a: pl.List(pl.String),
b: pl.Float64,
});
});
test("from row objects, with schema", () => {
const rows = [
{ num: 1, date: "foo", string: "foo1" },
Expand Down
33 changes: 19 additions & 14 deletions src/dataframe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1657,21 +1657,26 @@ fn obj_to_pairs(rows: &Array, len: usize) -> impl '_ + Iterator<Item = Vec<(Stri
if val.is_array().unwrap() {
let arr: napi::JsObject = unsafe { val.cast() };
let len = arr.get_array_length().unwrap();
// dont compare too many items, as it could be expensive
let max_take = std::cmp::min(len as usize, 10);
let mut dtypes: Vec<DataType> =
Vec::with_capacity(len as usize);

for idx in 0..max_take {
let item: napi::JsUnknown =
arr.get_element(idx as u32).unwrap();
let ty = item.get_type().unwrap();
let dt: Wrap<DataType> = ty.into();
dtypes.push(dt.0)
}
let dtype = coerce_data_type(&dtypes);

DataType::List(dtype.into())
if len == 0 {
DataType::List(DataType::Null.into())
} else {
// dont compare too many items, as it could be expensive
let max_take = std::cmp::min(len as usize, 10);
let mut dtypes: Vec<DataType> =
Vec::with_capacity(len as usize);

for idx in 0..max_take {
let item: napi::JsUnknown =
arr.get_element(idx as u32).unwrap();
let ty = item.get_type().unwrap();
let dt: Wrap<DataType> = ty.into();
dtypes.push(dt.0)
}
let dtype = coerce_data_type(&dtypes);

DataType::List(dtype.into())
}
} else if val.is_date().unwrap() {
DataType::Datetime(TimeUnit::Milliseconds, None)
} else {
Expand Down

0 comments on commit 9ae34f8

Please sign in to comment.