Built with Tutify.io

    AIStudyLabs

    Select Polars Columns by Index

    Select Polars Columns by Index

    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 –

    <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,

    <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,

    <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,

    <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,

    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,

    <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,

    <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

    <a id="h-references"></a>

    References