Built with Tutify.io

    AIStudyLabs

    How to Select Last Column of Polars DataFrame

    How to Select Last Column of Polars DataFrame

    In Polars, selecting the last column of a DataFrame means retrieving the column that appears at the final position (rightmost side) of the given DataFrame. This is helpful when the column names are unknown in advance or when you need to access the last column dynamically. It is particularly useful for datasets where column positions may change, allowing you to retrieve the most recently added or last column without specifying its name explicitly. In this article, I will demonstrate how to select the last column of a polars DataFrame.

    Key Points–

    <a id="h-usage-of-select-last-column-of-polars-dataframe"></a>

    Usage of Select Last Column of Polars DataFrame

    Selecting the last column of a Polars DataFrame is an essential operation in data manipulation, especially when you want to focus on the last attribute or when the number of columns is dynamic and you cannot rely on knowing the exact column name.

    To run some examples of how to select the last column of a polars DataFrame, let’s create a Polars DataFrame.

    
    import polars as pl
    
    technologies= {
        'Courses':["Spark","PySpark","Hadoop","Python","Pandas"],
        'Fees' :[22000,25000,23000,24000,26000],
        'Duration':['30days','50days','35days', '40days','55days'],
        'Discount':[1000,2300,1000,1200,2500]
              }
    df = pl.DataFrame(technologies)
    print("Original DataFrame:\n", df)
    

    Yields below output.

    To select the last column of the DataFrame using select() with pl.col(), you can specify the column dynamically by using df.columns[-1] in combination with pl.col() function.

    
    # Selecting the last column dynamically
    df2 = df.select(pl.col(df.columns[-1]))
    print("Last Column:\n", df2)
    

    Here,

    <a id="h-select-last-column-using-bracket-notation"></a>

    Select Last Column Using Bracket Notation []

    You can select the last column of a Polars DataFrame using bracket notation ([]). This method retrieves the last column as a Polars Series. To do so, you can access the column dynamically by its name, using df.columns[-1].

    
    # Selecting the last column 
    # Using bracket notation
    df2 = df[df.columns[-1]]
    print("Last Column (Series):\n", df2)
    
    # Output;
    # Last Column (Series):
    # shape: (5,)
    # Series: 'Discount' [i64]
    [
    	1000
    	2300
    	1000
    	1200
    	2500
    ]
    

    Here,

    This will give you the last column as a Polars Series. If you need it as a DataFrame, you can use the to_frame() method

    
    # Using to_frame() method
    df2 = df[df.columns[-1]].to_frame()
    print("Last Column:\n", df2)
    
    # Output:
    # Last Column:
    # shape: (5, 1)
    ┌──────────┐
    │ Discount │
    │ ---      │
    │ i64      │
    ╞══════════╡
    │ 1000     │
    │ 2300     │
    │ 1000     │
    │ 1200     │
    │ 2500     │
    └──────────┘
    

    <a id="h-select-last-column-using-get-column"></a>

    Select Last Column Using get_column()

    To select the last column of a Polars DataFrame using the get_column() method, pass the column name (which can be dynamically accessed with df.columns[-1]). This function returns the specified column as a Polars Series.

    
    # Selecting the last column using get_column()
    df2 = df.get_column(df.columns[-1])
    print("Last Column (Series):\n", df2)
    
    # Output:
    # Last Column (Series):
    # shape: (5,)
    # Series: 'Discount' [i64]
    [
    	1000
    	2300
    	1000
    	1200
    	2500
    ]
    

    Here,

    <a id="h-select-last-column-using-select-with-df-columns"></a>

    Select Last Column Using select() with df.columns

    You can use the select() method directly with df.columns to select the last column of a Polars DataFrame. This approach lets you specify the column name using df.columns[-1]. By referencing the column name through df.columns[-1], you can select the last column without needing to use pl.col().

    
    # Selecting the last column directly 
    # Using df.columns[-1]
    df2 = df.select(df.columns[-1])
    print("Last Column (DataFrame):\n", df2)
    
    # Output:
    # Last Column (DataFrame):
    # shape: (5, 1)
    ┌──────────┐
    │ Discount │
    │ ---      │
    │ i64      │
    ╞══════════╡
    │ 1000     │
    │ 2300     │
    │ 1000     │
    │ 1200     │
    │ 2500     │
    └──────────┘
    

    Here,

    <a id="h-selecting-the-last-column-using-with-columns-and-last"></a>

    Selecting the Last Column Using with_columns() and last()

    To select the last column of a Polars DataFrame using with_columns() and last(), you can use the with_columns() method, but instead of adding or modifying columns, you can use it in combination with last() to reference the last column dynamically.

    
    # Use .with_columns() and .last() to select the last column
    df2 = df.with_columns(pl.col(df.columns[-1]).alias("last_column"))
    print("Last Column (DataFrame):\n", df2)
    
    # Output:
    # Last Column (DataFrame):
    # shape: (5, 5)
    ┌─────────┬───────┬──────────┬──────────┬─────────────┐
    │ Courses ┆ Fees  ┆ Duration ┆ Discount ┆ last_column │
    │ ---     ┆ ---   ┆ ---      ┆ ---      ┆ ---         │
    │ str     ┆ i64   ┆ str      ┆ i64      ┆ i64         │
    ╞═════════╪═══════╪══════════╪══════════╪═════════════╡
    │ Spark   ┆ 22000 ┆ 30days   ┆ 1000     ┆ 1000        │
    │ PySpark ┆ 25000 ┆ 50days   ┆ 2300     ┆ 2300        │
    │ Hadoop  ┆ 23000 ┆ 35days   ┆ 1000     ┆ 1000        │
    │ Python  ┆ 24000 ┆ 40days   ┆ 1200     ┆ 1200        │
    │ Pandas  ┆ 26000 ┆ 55days   ┆ 2500     ┆ 2500        │
    └─────────┴───────┴──────────┴──────────┴─────────────┘
    

    Here,

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

    Conclusion

    In conclusion, selecting the last column of a Polars DataFrame can be done in various ways, depending on your preference for readability and functionality. Whether you choose bracket notation [], the to_series() method, get_column(), or select(), each approach efficiently allows you to dynamically access the last column.

    Happy Learning!!

    <a id="h-related-articles"></a>

    Related Articles

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

    References