datatable.first()

Return the first row for an Expr. If cols is an iterable, simply return the first element.

Parameters

cols
FExpr | iterable

Input columns or an iterable.

return
Expr | ...

One-row f-expression that has the same names, stypes and number of columns as cols. For an iterable the first element is returned.

Examples

Function first() called on a frame, that is an iterable of columns, returns the first column:

from datatable import dt, first, f, by DT = dt.Frame({"A": [1, 1, 2, 1, 2], "B": [None, 5, 3, 4, 2]})
AB
int32int32
01NA
115
223
314
422
first(DT)
A
int32
01
11
22
31
42

Called on a set of columns, first() returns the first row:

DT[:, first(f[:])]
AB
int32int32
01NA

The same could also be achieved by passing 0 to the row selector:

DT[0, :]
AB
int32int32
01NA

To get the first non-missing value in a column, one should additionally employ a corresponding i-filter:

DT[f.B != None, first(f.B)]
B
int32
05

Function first() is group-aware, meaning that it returns the first row per group in a by() context:

DT[:, first(f.B), by("A")]
AB
int32int32
01NA
123

To get the first non-missing value per group, one should first filter out all the missing values from the column in question:

DT[f.B != None, :][:, first(f.B), by("A")]
AB
int32int32
015
123

Note

Filtering out missing values in the row selector will not work in a general case, e.g. when one needs to find the first non-missing values in several columns.

See Also

  • last() – function that returns the last row.