Skip to content
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
35 changes: 35 additions & 0 deletions __tests__/series.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,41 @@
import pl, { DataType } from "@polars";
import Chance from "chance";

describe("mapElements", () => {
test("mapElements string", () => {
const mapping: Record<string, string> = {
A: "AA",
B: "BB",
C: "CC",
D: "OtherD",
};
const funcMap = (k: string): string => mapping[k] ?? "";
const actual = pl
.Series("foo", ["A", "B", "C", "D", "F", null], pl.String)
.mapElements(funcMap);
const expected = pl.Series(
"foo",
["AA", "BB", "CC", "OtherD", "", ""],
pl.String,
);
expect(actual).toSeriesEqual(expected);
});
test("mapElements int", () => {
const mapping: Record<number, number> = { 1: 11, 2: 22, 3: 33, 4: 44 };
const funcMap = (k: number): number => mapping[k] ?? "";
let actual = pl.Series("foo", [1, 2, 3, 5], pl.Int32).mapElements(funcMap);
let expected = pl.Series("foo", [11, 22, 33, null], pl.Int32);
expect(actual).toSeriesEqual(expected);
const multiFunc = (k: number): number => k * 2;
actual = pl.Series("foo", [1, 2, 3, 5], pl.Int32).mapElements(multiFunc);
expected = pl.Series("foo", [2, 4, 6, 10], pl.Int32);
expect(actual).toSeriesEqual(expected);
const funcStr = (k: number): string => `${k}x`;
actual = pl.Series("foo", [1, 2, 3, 5], pl.Int32).mapElements(funcStr);
expected = pl.Series("foo", ["1x", "2x", "3x", "5x"], pl.String);
expect(actual).toSeriesEqual(expected);
});
});
describe("from lists", () => {
test("bool", () => {
const expected = [[true, false], [true], [null], []];
Expand Down
25 changes: 25 additions & 0 deletions polars/series/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,28 @@ export interface Series<T extends DataType = any, Name extends string = string>
* ```
*/
limit(n?: number): Series;
/**
* Map a custom/user-defined function (UDF) over elements in this Series.
* @param fn - Custom function to call
*
* @example
* ```
* > const mapping: Record<string, string> = { A: 'AA', B: 'BB', C: 'CC', D: 'OtherD', };
* > const funcMap = (k: string): string => mapping[k] ?? '';
* > pl.Series("foo", ["A", "B", "C", "D", "F", null], pl.String).mapElements(funcMap);
shape: (6,)
Series: 'foo' [str]
[
"AA"
"BB"
"CC"
"OtherD"
""
""
]
* ```
*/
mapElements(fn: (v: any) => any): Series;
/**
* Get the maximum value in this Series.
* @example
Expand Down Expand Up @@ -1612,6 +1634,9 @@ export function _Series(_s: any): Series {
limit(n = 10) {
return wrap("limit", n);
},
mapElements(fn: (v: any) => any) {
return Series(this.name, [...this.values()].map(fn));
},
max() {
return _s.max() as any;
},
Expand Down