In Polars, selecting columns by index allows you to access specific columns in a DataFrame based on their labels (names) or positions (indices). You can use select(), df[], and df.columns[] to select a single column or multiple columns by index position.
In this article, I will explain various methods to select one or more columns from a Polars DataFrame, including selection by column labels, index positions, and ranges.
Key Points –
- Use
df.select(pl.nth(index))ordf.select([df.columns[index]])to retrieve a single column by index. - Use indexing (
df[:, index]) to select a column by its position. - Use slicing (
df[:, start:end]) to retrieve a range of columns. - Use a list of indices (
df[:, [index1, index2]]) to select specific columns. - Use negative indexing (
df[:, -N:]) to dynamically select the last N columns. - Use step
slicing (df[:, ::step])to select every N-th column. - Use
df.select(pl.col(df.columns[start:end]))for flexible selection. - Use
df.columns[index]to retrieve column names before selecting.
<a id="h-usage-of-select-polars-columns-by-index"></a>
Usage of Select Polars Columns by Index
Selecting columns by index in Polars is helpful when dealing with datasets where column positions are fixed, but names may vary dynamically. Depending on your needs, you can use different techniques to select a single column, multiple consecutive columns, non-consecutive columns, or columns at regular intervals.
First, let’s create a Polars DataFrame.
import polars as pl
technologies= ({
'Courses':["spark","python","pandas"],
'Fees' :[22000,25000,24000],
'Duration':['30days','60days','50days'],
'Discount':[1000,2000,2500]
})
df = pl.DataFrame(technologies)
print("Original DataFrame:\n", df)
Yields below output.
If you want to select a single column by index, you should use df.select(df.columns[index]). For instance, it selects the "Courses" column and returns a new DataFrame with the chosen columns.
# Select the first column by index
result = df.select(df.columns[0])
print("Selected Column:\n", result)
The pl.nth(0) selects a single row based on its index, not columns. It works like selecting the first row from a DataFrame.
# Select the first row (index 0)
result = df.select(pl.nth(0))
print("Selected Column:\n", result)
Here,
pl.nth(0)selects the first row from all columns.- If you want multiple rows, use
pl.nth(range(start, end)).
<a id="h-select-multiple-consecutive-columns-by-index"></a>
Select Multiple Consecutive Columns by Index
To select multiple consecutive columns by index, you can use slicing on df.columns inside df.select() function.
# Select first two columns (Index 1 and 3)
result = df.select(df.columns[1:3])
print("Selected Columns:\n", result)
# Select multiple consecutive columns (index 1 to 2)
result = df[:, 1:3]
print("Selected Columns:\n", result)
# Output:
# Selected Columns:
# shape: (3, 2)
┌───────┬──────────┐
│ Fees ┆ Duration │
│ --- ┆ --- │
│ i64 ┆ str │
╞═══════╪══════════╡
│ 22000 ┆ 30days │
│ 25000 ┆ 60days │
│ 24000 ┆ 50days │
└───────┴──────────┘
Here,
df.columns[1:3]extracts column names from index1to3(['Fees','Duration']).df.select([…])selects the extracted columns and returns a new DataFrame.- Slicing works just like lists in Python
[start:end](end is exclusive).
<a id="h-list-of-indices-using-df-select-pl-nth-range"></a>
List of Indices Using df.select(pl.nth(range()))
The pl.nth(range(0, 2)) function selects rows from index 0 to 1 (not columns) in Polars. It works like row slicing, similar to df[0:2] in pandas.
# Selecting first two rows (indices 0 and 1)
result = df.select(pl.nth(range(0, 2)))
print("Selected Column:\n", result)
# Output:
# Selected Column:
# shape: (3, 2)
┌─────────┬───────┐
│ Courses ┆ Fees │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════════╪═══════╡
│ spark ┆ 22000 │
│ python ┆ 25000 │
│ pandas ┆ 24000 │
└─────────┴───────┘
Here,
pl.nth(range(0, 2))selects multiple rows based on the specified range.- Returns rows with index
0and1from the DataFrame. - If you want columns by index, use
df.select(df.columns[start:end]).
<a id="h-select-dataframe-columns-by-name"></a>
Select DataFrame Columns by Name
To select columns from a DataFrame by name, you can directly use square brackets []. For example, df[['Courses', 'Fee', 'Duration']] extracts only the Courses, Fees, and Duration columns from the DataFrame df.
# Select Columns by labels
df2 = df[["Courses","Fees","Duration"]]
print("Select columns by labels:\n", df2)
# Output:
# Select columns by labels:
# shape: (3, 3)
┌─────────┬───────┬──────────┐
│ Courses ┆ Fees ┆ Duration │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str │
╞═════════╪═══════╪══════════╡
│ spark ┆ 22000 ┆ 30days │
│ python ┆ 25000 ┆ 60days │
│ pandas ┆ 24000 ┆ 50days │
└─────────┴───────┴──────────┘
<a id="h-select-non-consecutive-columns-by-index"></a>
Select Non-Consecutive Columns by Index
You can select non-consecutive columns by their index positions in polars using list-based indexing (df[:, [index1, index2]]) or the select() function.
# Select non-consecutive columns
result = df[:, [0, 2]]
print("Selected Columns:\n", result)
# Output:
# Selected Columns:
# shape: (3, 2)
┌─────────┬──────────┐
│ Courses ┆ Duration │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪══════════╡
│ spark ┆ 30days │
│ python ┆ 60days │
│ pandas ┆ 50days │
└─────────┴──────────┘
Here,
df[:, [0, 2]]selects columns at index 0 (Courses) and index 2 (Duration).- This method is useful when selecting columns that are not next to each other.
You can select non-adjacent columns using select() method along with pl.col() function. This method is more readable and dynamic because it allows selection based on column names derived from their index positions.
# Select non-consecutive columns
result = df.select(pl.col([df.columns[0], df.columns[2]]))
print("Selected Columns:\n", result)
This example yields the above output.
<a id="h-select-the-last-n-columns"></a>
Select the Last N Columns
If you want to select the last N columns dynamically, use df.columns[-N:] to get the column names and pass them to pl.col() function.
# Number of last columns to select
N = 2
# Select the last N columns dynamically
result = df.select(pl.col(df.columns[-N:]))
print("Selected Columns:\n", result)
# Select the last 2 columns
result = df.select(df.columns[-2:])
print("Selected Columns:\n", result)
# Output:
# Selected Columns:
# shape: (3, 2)
┌──────────┬──────────┐
│ Duration ┆ Discount │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════════╪══════════╡
│ 30days ┆ 1000 │
│ 60days ┆ 2000 │
│ 50days ┆ 2500 │
└──────────┴──────────┘
Here,
df.columns[-N:]retrieves the lastNcolumn names dynamically.pl.col(df.columns[-N:])selects those columns.select(…)returns a new DataFrame with only the lastNcolumns.
<a id="h-select-every-alternate-column-step-selection"></a>
Select Every Alternate Column (Step Selection)
You can select every alternate column (or every N-th column) using select() method along with Python list slicing (df.columns[::step]).
# Step size (every 2nd column)
step = 2
# Select every alternate column using step selection
result = df.select(pl.col(df.columns[::step]))
print("Selected Columns:\n", result)
# Select every alternate column (Step = 2)
result = df.select(df.columns[::2])
print("Selected Columns:\n", result)
# Output:
# Selected Columns:
# shape: (3, 2)
┌─────────┬──────────┐
│ Courses ┆ Duration │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪══════════╡
│ spark ┆ 30days │
│ python ┆ 60days │
│ pandas ┆ 50days │
└─────────┴──────────┘
Here,
df.columns[::step]selects every second column by skipping one in between (indexes 0, 2, 4, …). Withstep = 2, it picks the"Courses"column at index0and the"Duration"column at index2.pl.col(df.columns[::step])selects only the required columns.
<a id="h-conclusion"></a>
Conclusion
In conclusion, selecting columns by index in Polars is a powerful technique for efficient data manipulation. Whether you need to extract a single column, multiple consecutive columns, non-consecutive columns, or use step-based selection, Polars provides multiple flexible methods.
Happy Learning!!
<a id="h-related-articles"></a>
Related Articles
- Append or Concatenate Two DataFrames in Polars
- Convert Polars Cast Integer to Float
- Convert Polars Cast Float to Integer
- Polars Sum Multiple Columns
- How to Drop Row in Polars
- How to drop a column using Polars
- Add New Columns to Polars DataFrame
- How to Select Columns by Data Type in Polars
- Polars Filter DataFrame with Multilple Conditions
- How to Convert String to Date or Datetime in Polars
- Reorder Columns in a Specific Order Using Polars
<a id="h-references"></a>
