Skip to content

Get column by index

Source code

Description

Extract a DataFrame column (by index) as a Polars series. Unlike get_column(), this method will not fail but will return a NULL if the index doesn’t exist in the DataFrame. Keep in mind that Polars is 0-indexed so "0" is the first column.

Usage

<DataFrame>$to_series(idx = 0)

Arguments

idx Index of the column to return as Series. Defaults to 0, which is the first column.

Value

Series or NULL

Examples

library(polars)

df = pl$DataFrame(iris[1:10, ])

# default is to extract the first column
df$to_series()
#> polars Series: shape: (10,)
#> Series: 'Sepal.Length' [f64]
#> [
#>  5.1
#>  4.9
#>  4.7
#>  4.6
#>  5.0
#>  5.4
#>  4.6
#>  5.0
#>  4.4
#>  4.9
#> ]
# Polars is 0-indexed, so we use idx = 1 to extract the *2nd* column
df$to_series(idx = 1)
#> polars Series: shape: (10,)
#> Series: 'Sepal.Width' [f64]
#> [
#>  3.5
#>  3.0
#>  3.2
#>  3.1
#>  3.6
#>  3.9
#>  3.4
#>  3.4
#>  2.9
#>  3.1
#> ]
# doesn't error if the column isn't there
df$to_series(idx = 8)
#> NULL