The to_series
method in Polars is used to select a column from a DataFrame and return it as a
The syntax for the to_series
method is as follows:
DataFrame.to_series(index: int = 0)
index (int)
: This is the location of the column to be selected as a Series.
Here’s an example of how we can use the to_series
method:
import polars as pl# Create a DataFramedata = {'name': ['Edith', 'William', 'Oliver'],'age': [45, 30, 55],'city': ['Bristol', 'Manchester', 'Salford']}df = pl.DataFrame(data)# 1. using .to_series() on .select()series_by_select = df.select('name').to_series()print(series_by_select)# 2. using .to_series() alone with specifying column indexseries_by_index = df.to_series(1)print(series_by_index)
Here’s the step-by-step explanation of the code:
Lines 4–8: We create a DataFrame using the provided data
dictionary. Each key in the dictionary corresponds to a column name, and the associated values are lists representing the column data.
Lines 10–11: We select the name
column from the DataFrame using the select('name')
method and then convert the resulting DataFrame to a Series using the to_series()
method. The resulting series is then printed and named series_by_select
.
Lines 14–15: The DataFrame converts to a Series using the to_series()
method, and the index 1
is specified to choose the column at index 1
(which is the age
column). The resulting Series is then printed and named series_by_index
.
The to_series
method in Polars provides a convenient way to select a specific column from a DataFrame based on its index location and work with it as a standalone Series. This enhances the flexibility of data manipulation and analysis within the Polars library.
Free Resources