Initializing playground…
← Back to roadmap

🔢 nlargest / nsmallest — Interactive Playground

Return the n largest or smallest values — mirrors pandas.Series.nlargest(), Series.nsmallest(), DataFrame.nlargest(), and DataFrame.nsmallest().
Edit any code block below and press ▶ Run (or Ctrl+Enter) to execute it live in your browser.

1 · Series.nlargest basics

nlargestSeries(s, n) returns a new Series containing the n largest values, sorted in descending order. NaN / null values are always excluded.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

2 · Series.nsmallest basics

nsmallestSeries(s, n) returns the n smallest values sorted in ascending order.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

3 · The keep parameter

When there are ties at the selection boundary, keep controls which ones survive: first (default), last, or all (may return more than n rows).

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

4 · Labeled index preservation

The result preserves the original labels, not a reset 0-based index.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

5 · NaN / null handling

Missing values are silently excluded from both the selection and the result.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

6 · DataFrame.nlargest

nlargestDataFrame(df, n, { columns }) returns the n rows with the largest values in the given column(s), sorted descending. Multiple columns provide a lexicographic tie-breaker.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

7 · DataFrame.nsmallest

nsmallestDataFrame(df, n, { columns }) returns the rows with the smallest values, sorted ascending.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

8 · Edge cases

Behavior when n exceeds the series length, n is zero, all values are NaN, or values are strings.

TypeScript
Click ▶ Run to execute
Ctrl+Enter to run · Tab to indent

API Reference

Both Series and DataFrame variants accept an options object for tie-breaking and column selection.

// Series
nlargestSeries(series, n, {
  keep?: "first" | "last" | "all",  // default "first"
}): Series

nsmallestSeries(series, n, {
  keep?: "first" | "last" | "all",  // default "first"
}): Series

// DataFrame
nlargestDataFrame(df, n, {
  columns: string | string[],       // column(s) to sort by
  keep?:   "first" | "last" | "all",
}): DataFrame

nsmallestDataFrame(df, n, {
  columns: string | string[],
  keep?:   "first" | "last" | "all",
}): DataFrame