Index Slicing

Unlike tools like pandas which has indexing, Polars doesn't use indexing however, we can use indeces to fetch data and value. Let's demonstrate how this can be achieved.

import polars as pl 

data = pl.read_csv("data/employees.csv")
print(data.head())
OUTPUTshape: (5, 6) ┌─────┬────────┬──────┬─────────────┬────────┬────────────┐ │ id ┆ name ┆ age ┆ department ┆ salary ┆ join_date │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ f64 ┆ str ┆ i64 ┆ str │ ╞═════╪════════╪══════╪═════════════╪════════╪════════════╡ │ 1 ┆ User_1 ┆ null ┆ null ┆ 123355 ┆ 2020-01-01 │ │ 2 ┆ User_2 ┆ 28.0 ┆ Sales ┆ 118399 ┆ 2020-01-02 │ │ 3 ┆ User_3 ┆ 29.0 ┆ Sales ┆ 88727 ┆ 2020-01-03 │ │ 4 ┆ User_4 ┆ 48.0 ┆ Engineering ┆ 71572 ┆ 2020-01-04 │ │ 5 ┆ User_5 ┆ 22.0 ┆ Engineering ┆ 81849 ┆ 2020-01-05 │ └─────┴────────┴──────┴─────────────┴────────┴────────────┘
data.shape
OUTPUT(100, 6)

row()

We can use the row() method that fetches the individual rows from the data. In the example below, we fetch the first column.

data.row(0)
OUTPUT(1, 'User_1', None, None, 123355, '2020-01-01')

We notice that we now have the first row returned as a tuple. We can then fetch the specific item.

data.row(0)[5]
OUTPUT'2020-01-01'

rows as dictionary

We can also return each row of data as a dictionary where the column names represent the key for the dictionary.

# Get a single row as a dictionary
row_dict = data.row(0, named=True)
print(row_dict)
OUTPUT{'id': 1, 'name': 'User_1', 'age': None, 'department': None, 'salary': 123355, 'join_date': '2020-01-01'}

item()

The item() object is the method used to extract values directly from the dataframe.

value = data.filter(pl.col("id") == 3).select("age").item()
value
OUTPUT29.0