Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing skip_rows bug and adding scanCSV options #147

Merged
merged 3 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
47 changes: 43 additions & 4 deletions __tests__/io.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import fs from "fs";
// eslint-disable-next-line no-undef
const csvpath = path.resolve(__dirname, "./examples/datasets/foods1.csv");
// eslint-disable-next-line no-undef
const emptycsvpath = path.resolve(__dirname, "./examples/datasets/empty.csv");
// eslint-disable-next-line no-undef
const parquetpath = path.resolve(__dirname, "./examples/foods.parquet");
// eslint-disable-next-line no-undef
const avropath = path.resolve(__dirname, "./examples/foods.avro");
Expand Down Expand Up @@ -63,13 +65,35 @@ describe("read:csv", () => {
csvBuffer.toString("utf-8").slice(0, 22),
);
});
it("can read csv with ragged lines", () => {
const csvBuffer = Buffer.from("A\nB\nC,ragged\n", "utf-8");
let df = pl.readCSV(csvBuffer);
const expected = `shape: (2, 1)
┌─────┐
│ A │
│ --- │
│ str │
╞═════╡
│ B │
│ C │
└─────┘`;
expect(df.toString()).toEqual(expected);
const f = () => {
df = pl.readCSV(csvBuffer, { truncateRaggedLines: false });
};
expect(f).toThrow();
});
it("can load empty csv", () => {
const df = pl.readCSV(emptycsvpath, { raiseIfEmpty: false });
expect(df.shape).toEqual({ height: 0, width: 0 });
});
it("can parse datetimes", () => {
const csv = `timestamp,open,high
2021-01-01 00:00:00,0.00305500,0.00306000
2021-01-01 00:15:00,0.00298800,0.00300400
2021-01-01 00:30:00,0.00298300,0.00300100
2021-01-01 00:45:00,0.00299400,0.00304000`;
const df = pl.readCSV(csv, { parseDates: true });
const df = pl.readCSV(csv, { tryParseDates: true });
expect(df.dtypes.map((dt) => dt.toJSON())).toEqual([
pl.Datetime("us").toJSON(),
pl.Float64.toJSON(),
Expand Down Expand Up @@ -159,21 +183,36 @@ describe("scan", () => {
expect(df.shape).toEqual({ height: 27, width: 4 });
});
it("can lazy load (scan) from a csv file with options", () => {
const df = pl
let df = pl
.scanCSV(csvpath, {
hasHeader: false,
skipRows: 1,
skipRows: 2,
nRows: 4,
})
.collectSync();

expect(df.shape).toEqual({ height: 4, width: 4 });

df = pl
.scanCSV(csvpath, {
hasHeader: true,
skipRows: 2,
nRows: 4,
})
.collectSync();

expect(df.shape).toEqual({ height: 4, width: 4 });
});

it("can lazy load empty csv", () => {
const df = pl.scanCSV(emptycsvpath, { raiseIfEmpty: false }).collectSync();
expect(df.shape).toEqual({ height: 0, width: 0 });
});

it("can lazy load (scan) from a parquet file with options", () => {
pl.readCSV(csvpath, {
hasHeader: false,
skipRows: 1,
skipRows: 2,
nRows: 4,
}).writeParquet(parquetpath);

Expand Down
55 changes: 25 additions & 30 deletions __tests__/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,15 @@ expect.extend({
message: () => "series matches",
pass: true,
};
} else {
return {
message: () => `
}
return {
message: () => `
Expected:
>>${expected}
Received:
>>${actual}`,
pass: false,
};
}
pass: false,
};
},
toSeriesEqual(actual, expected) {
const pass = actual.seriesEqual(expected);
Expand All @@ -27,16 +26,15 @@ Received:
message: () => "series matches",
pass: true,
};
} else {
return {
message: () => `
}
return {
message: () => `
Expected:
>>${expected}
Received:
>>${actual}`,
pass: false,
};
}
pass: false,
};
},
toFrameEqual(actual, expected, nullEqual?) {
const pass = actual.frameEqual(expected, nullEqual);
Expand All @@ -45,16 +43,15 @@ Received:
message: () => "dataframes match",
pass: true,
};
} else {
return {
message: () => `
}
return {
message: () => `
Expected:
>>${expected}
Received:
>>${actual}`,
pass: false,
};
}
pass: false,
};
},
toFrameStrictEqual(actual, expected) {
const frameEq = actual.frameEqual(expected);
Expand All @@ -64,16 +61,15 @@ Received:
message: () => "dataframes match",
pass: true,
};
} else {
return {
message: () => `
}
return {
message: () => `
Expected:
>>${expected}
Received:
>>${actual}`,
pass: false,
};
}
pass: false,
};
},
toFrameEqualIgnoringOrder(act: pl.DataFrame, exp: pl.DataFrame) {
const actual = act.sort(act.columns.sort());
Expand All @@ -84,16 +80,15 @@ Received:
message: () => "dataframes match",
pass: true,
};
} else {
return {
message: () => `
}
return {
message: () => `
Expected:
>>${expected}
Received:
>>${actual}`,
pass: false,
};
}
pass: false,
};
},
});

Expand Down
49 changes: 18 additions & 31 deletions polars/dataframe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1708,9 +1708,8 @@ export interface DataFrame
function prepareOtherArg(anyValue: any): Series {
if (Series.isSeries(anyValue)) {
return anyValue;
} else {
return Series([anyValue]) as Series;
}
return Series([anyValue]) as Series;
}

function map(df: DataFrame, fn: (...args: any[]) => any[]) {
Expand Down Expand Up @@ -1841,9 +1840,8 @@ export const _DataFrame = (_df: any): DataFrame => {
df.getColumns().map((s) => {
if (s.isNumeric() || s.isBoolean()) {
return s.cast(DataType.Float64);
} else {
return s;
}
return s;
}),
);
};
Expand Down Expand Up @@ -1877,9 +1875,8 @@ export const _DataFrame = (_df: any): DataFrame => {
dropNulls(...subset) {
if (subset.length) {
return wrap("dropNulls", subset.flat(2));
} else {
return wrap("dropNulls");
}
return wrap("dropNulls");
},
distinct(opts: any = false, subset?, keep = "first") {
return this.unique(opts, subset);
Expand Down Expand Up @@ -2037,9 +2034,8 @@ export const _DataFrame = (_df: any): DataFrame => {
max(axis = 0) {
if (axis === 1) {
return _Series(_df.hmax() as any) as any;
} else {
return wrap("max");
}
return wrap("max");
},
mean(axis = 0, nullStrategy = "ignore") {
if (axis === 1) {
Expand All @@ -2057,9 +2053,8 @@ export const _DataFrame = (_df: any): DataFrame => {
min(axis = 0) {
if (axis === 1) {
return _Series(_df.hmin() as any) as any;
} else {
return wrap("min");
}
return wrap("min");
},
nChunks() {
return _df.nChunks();
Expand Down Expand Up @@ -2168,28 +2163,25 @@ export const _DataFrame = (_df: any): DataFrame => {
false,
seed,
);
} else {
throw new TypeError("must specify either 'frac' or 'n'");
}
throw new TypeError("must specify either 'frac' or 'n'");
},
select(...selection) {
const hasExpr = selection.flat().some((s) => Expr.isExpr(s));
if (hasExpr) {
return _DataFrame(_df).lazy().select(selection).collectSync();
} else {
return wrap("select", columnOrColumnsStrict(selection as any));
}
return wrap("select", columnOrColumnsStrict(selection as any));
},
shift: (opt) => wrap("shift", opt?.periods ?? opt),
shiftAndFill(n: any, fillValue?: number | undefined) {
if (typeof n === "number" && fillValue) {
return _DataFrame(_df).lazy().shiftAndFill(n, fillValue).collectSync();
} else {
return _DataFrame(_df)
.lazy()
.shiftAndFill(n.n, n.fillValue)
.collectSync();
}
return _DataFrame(_df)
.lazy()
.shiftAndFill(n.n, n.fillValue)
.collectSync();
},
shrinkToFit(inPlace: any = false): any {
if (inPlace) {
Expand Down Expand Up @@ -2408,9 +2400,8 @@ export const _DataFrame = (_df: any): DataFrame => {
}
if (!options?.columnNames) {
return wrap("transpose", keep_names_as, undefined);
} else {
return wrap("transpose", keep_names_as, options.columnNames);
}
return wrap("transpose", keep_names_as, options.columnNames);
},
unnest(names) {
names = Array.isArray(names) ? names : [names];
Expand All @@ -2428,28 +2419,25 @@ export const _DataFrame = (_df: any): DataFrame => {
withColumn(column: Series | Expr) {
if (Series.isSeries(column)) {
return wrap("withColumn", column.inner());
} else {
return this.withColumns(column);
}
return this.withColumns(column);
},
withColumns(...columns: (Expr | Series)[]) {
if (isSeriesArray(columns)) {
return columns.reduce(
(acc, curr) => acc.withColumn(curr),
_DataFrame(_df),
);
} else {
return this.lazy()
.withColumns(columns)
.collectSync({ noOptimization: true, stringCache: false });
}
return this.lazy()
.withColumns(columns)
.collectSync({ noOptimization: true, stringCache: false });
},
withColumnRenamed(opt, replacement?) {
if (typeof opt === "string") {
return this.rename({ [opt]: replacement });
} else {
return this.rename({ [opt.existing]: opt.replacement });
}
return this.rename({ [opt.existing]: opt.replacement });
},
withRowCount(name = "row_nr") {
return wrap("withRowCount", name);
Expand Down Expand Up @@ -2477,9 +2465,8 @@ export const _DataFrame = (_df: any): DataFrame => {
}
if (typeof prop !== "symbol" && !Number.isNaN(Number(prop))) {
return target.row(Number(prop));
} else {
return Reflect.get(target, prop, receiver);
}
return Reflect.get(target, prop, receiver);
},
set(target: DataFrame, prop, receiver) {
if (Series.isSeries(receiver)) {
Expand Down
Loading