Sub topic 1
DataFrames and Series: the basic containers
Polars stores tabular data in two containers: the Series, which holds one column, and the DataFrame, which holds several columns of equal length. Everything else in the library, including expressions, contexts, joins and the lazy API, operates on these two types. This chapter covers how to create them, how to inspect them, and how they differ from the pandas containers you may already know.
Prerequisites
This chapter assumes you have the following:
- Basic Python: functions, lists, dictionaries and method chaining.
- Familiarity with tabular data: rows, columns and CSV files.
- A working installation of Polars (
pip install polars). - Optional: prior experience with pandas or SQL. Comparisons to pandas appear in a few places, but you can skip them.
The working model
A Series is a named, one-dimensional sequence of values that all share one data type. A DataFrame is an ordered collection of Series that all have the same length. Each column keeps its own type, so a DataFrame can mix integers, strings and dates.
Polars stores each column in a contiguous block of memory, following the Apache Arrow columnar format. Operations that touch one column read one block. This is why Polars encourages you to think in columns instead of rows.
Two properties set Polars apart from pandas:
- There is no row index. Rows are identified only by position. If you need a row label, store it in an ordinary column.
- Columns are not mutated in place. Operations return new DataFrames, and Polars shares unchanged columns between the old and new frames instead of copying them.
Creating a Series
Pass a name and a list of values. The name comes first.
import polars as pl
s = pl.Series("salary", [120, 100, 80, 90])
print(s)
print(s.dtype)
print(s.len())
print(s.mean())Polars infers the type from the values. Here it picks Int64. You can set the type yourself with the dtype argument.
small = pl.Series("salary", [120, 100, 80, 90], dtype=pl.Int16)
print(small.dtype)Series support arithmetic and comparison. These operations act on every element at once and return a new Series.
raised = s * 1.1
mask = s >= 90
print(raised)
print(mask)The second result is a Series of Boolean values. Later chapters use boolean results like this inside filter.
Creating a DataFrame
The most common constructor takes a dictionary. Each key becomes a column name, and each value is a list that becomes that column.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
print(df)
print(df.schema)The printed table shows each column's name and data type under the header, then the values. The schema attribute maps each column name to its type. In current Polars versions it is an ordered mapping, so the column order is preserved.
All lists must have the same length. If they differ, Polars raises an error instead of padding the shorter ones.
You can build a DataFrame from other sources too:
| Source | Constructor | Notes |
|---|---|---|
| List of dictionaries | `pl.DataFrame([{"a": 1}, {"a": 2}])` | Keys become column names. |
| List of rows | `pl.DataFrame(rows, schema=["a", "b"], orient="row")` | Needs column names and `orient="row"`. |
| NumPy array | `pl.DataFrame(arr, schema=["a", "b"])` | The array's dtype applies to every column. |
| CSV file | `pl.read_csv("file.csv")` | Covered in a later chapter. |
Building from rows works but is slower than building from columns. The data is stored by column, so Polars must rearrange row data on the way in.
Inspecting a DataFrame
These attributes and methods answer the questions you ask first about an unfamiliar frame.
print(df.shape) # (rows, columns)
print(df.height) # number of rows
print(df.width) # number of columns
print(df.columns) # list of column names
print(df.dtypes) # list of data types
print(df.head(2)) # first two rows
print(df.tail(2)) # last two rows
print(df.describe()) # summary statistics per column
print(df.glimpse()) # compact view, one line per columnglimpse() prints the view and returns None, so print(df.glimpse()) also prints None. Call df.glimpse() on its own line in real code.
describe() reports count, null count, mean, standard deviation, min, quartiles and max. For string columns the numeric statistics show as null.
Getting a Series out of a DataFrame
Three forms return a column as a Series:
col_a = df["salary"]
col_b = df.get_column("salary")
col_c = df.to_series(2) # by position
print(col_a.name, col_b.dtype, col_c.len())Square brackets with a string return a Series, not a DataFrame. This is convenient in exploration. In pipelines, prefer expressions such as pl.col("salary"), which the next chapters cover. An expression describes a computation and lets Polars plan and optimize the work. A Series pulled out by hand is just data.
To get a single-column DataFrame, pass a list: df.select("salary").
Getting values out
Moving data out of Polars is sometimes necessary, for example when handing it to a plotting library or to plain Python code.
print(df.to_dicts()) # list of row dictionaries
print(df.to_dict(as_series=False)) # dict of column lists
print(df.row(0)) # one row as a tuple
print(df["salary"].to_list()) # one column as a Python listExtracting values one row at a time in a Python loop gives up the speed advantage of columnar storage. If you find yourself writing for row in df.iter_rows() to compute a new column, an expression almost always does the same job faster. The last chapter returns to this.
Replacing and adding columns
A DataFrame is not changed by methods that return a new frame. These two lines show the difference.
df.with_columns((pl.col("salary") * 2).alias("double"))
print(df.columns) # unchanged: ['name', 'dept', 'salary']
df = df.with_columns((pl.col("salary") * 2).alias("double"))
print(df.columns) # now includes 'double'The first call builds a new frame and discards it. You must assign the result to keep it.
Item assignment such as df["double"] = ... is not supported in Polars. Use with_columns. Chapter 4 covers contexts in detail.
Common errors
- Mismatched lengths.
pl.DataFrame({"a": [1, 2], "b": [1]})fails. Make every column the same length, or use a single-element Series only where a scalar broadcast is documented. - Forgetting to assign. Methods return new frames. If a column seems missing, check that you captured the return value.
- Mixed types in one list. A list such as
[1, "two", 3.0]has no common type. Recent versions raise a type error unless you passstrict=Falseand accept that values are coerced or become null. - Expecting a pandas index. Code that relies on
df.loc[label]or on index alignment has no Polars equivalent. Use a column and a filter or a join. - Column names must be unique. Creating a DataFrame with duplicate names raises a duplicate error.
Quick comparison with pandas
| Concept | pandas | Polars |
|---|---|---|
| Row labels | Index, can be any type | None, rows are positional |
| Column access | `df["a"]` returns a Series | `df["a"]` returns a Series |
| In-place edits | `df["b"] = ...` | Not supported, use `with_columns` |
| Missing values | `NaN` and `None` mixed | `null` for every type |
| Memory layout | NumPy blocks | Arrow columns |
Check your understanding
Exercise
You run df.with_columns((pl.col("salary") / 12).alias("monthly")) on its own line and then print df.columns. The new column is missing. Why, and how do you fix it?
Show answer
DataFrame methods return a new DataFrame and leave the original unchanged. The result of the call was discarded. Assign it back with df = df.with_columns(...), or store it in a new variable.
Exercise
What is the difference between df["salary"] and df.select("salary")?
Show answer
df["salary"] returns a Series, a one-dimensional container with a name and a type. df.select("salary") returns a DataFrame with a single column.
Exercise
Create a Series named scores with the values 3.5, 4.0 and 2.5, and then create a DataFrame with that Series as a column plus a student column holding "a", "b" and "c". Print its shape.
Show answer
One solution: import polars as pl scores = pl.Series("scores", [3.5, 4.0, 2.5]) frame = pl.DataFrame({"student": ["a", "b", "c"], "scores": scores}) print(frame.shape) # (3, 2) A Series can be passed as a dictionary value, and its own name is replaced by the dictionary key.