Built with Tutify.io

    AIStudyLabs

    How to Get the Name of an Aliased Expression in Polars?

    How to Get the Name of an Aliased Expression in Polars?

    In Polars, applying alias("new_name") to a computed or transformed column assigns a custom name to that expression. This is particularly helpful when working with expressions, lazy frames, or chaining multiple operations. In scenarios where you're building expressions dynamically or troubleshooting your logic, it can be useful to retrieve the name of an aliased expression. In this article, I will explain how to get the name of an aliased expression in polars.

    Key Points –

    <a id="h-usage-of-get-the-name-of-an-aliased-expression-in-polars"></a>

    Usage of Get the Name of an Aliased Expression in Polars

    An aliased expression in Polars is a way to assign a custom name to the result of a computation or transformation using the alias() method. When you perform operations on one or more columns, the resulting output may have a default or unclear name. By using alias("new_name"), you can label the result with a meaningful and readable name for easier interpretation and further processing.

    Now, let’s create a Polars DataFrame.

    
    import polars as pl
    
    # Creating a dictionary with data about courses
    technologies = {
        'Courses': ["Spark", "Hadoop", "Python", "Pandas"],
        'Fees': [22000, 25000, 20000, 26000],
        'Discount': [1000, 1500, 1200, 2500]
    }
    
    # Convert dictionary to Polars DataFrame
    df = pl.DataFrame(technologies)
    
    # Print the DataFrame
    print("Original DataFrame:\n", df)
    

    Yields below output.

    If you want to perform a simple arithmetic operation on columns in your Polars DataFrame and assign a new name to the result, you can do so by applying the operation and using an alias to name the resulting column.

    
    # Create a new expression that adds 10 to Fees and alias it
    updated_fees_expr = (pl.col("Fees") + 100).alias("Updated_Fees")
    
    # Select the original columns plus the new aliased expression
    result = df.select([
        pl.col("Courses"),
        pl.col("Fees"),
        updated_fees_expr
    ])
    print(result)
    

    Here,

    <a id="h-multiplication-with-alias"></a>

    Multiplication with Alias

    If you want to perform a multiplication between columns (or with a constant) and store the result as a new column with a custom name, you can use an alias. For instance, to compute the total discount by multiplying the Discount column by 2 and name the new column "Double_Discount".

    
    # Multiply Discount by 2 and alias as 'Double_Discount'
    df2 = df.with_columns(
        (pl.col("Discount") * 2).alias("Double_Discount")
    )
    print(df2)
    
    # Multiply Fees by 2 and alias the result
    double_fees_expr = (pl.col("Discount") * 2).alias("Double_Discount")
    
    # Select original columns plus the new aliased expression
    result = df.select([
        pl.col("Courses"),
        pl.col("Fees"),
        double_fees_expr
    ])
    print(result)
    
    # Output:
    # shape: (4, 4)
    ┌─────────┬───────┬──────────┬─────────────────┐
    │ Courses ┆ Fees  ┆ Discount ┆ Double_Discount │
    │ ---     ┆ ---   ┆ ---      ┆ ---             │
    │ str     ┆ i64   ┆ i64      ┆ i64             │
    ╞═════════╪═══════╪══════════╪═════════════════╡
    │ Spark   ┆ 22000 ┆ 1000     ┆ 2000            │
    │ Hadoop  ┆ 25000 ┆ 1500     ┆ 3000            │
    │ Python  ┆ 20000 ┆ 1200     ┆ 2400            │
    │ Pandas  ┆ 26000 ┆ 2500     ┆ 5000            │
    └─────────┴───────┴──────────┴─────────────────┘
    

    Here,

    <a id="h-string-manipulation-with-alias"></a>

    String Manipulation With Alias

    String manipulation with aliasing in Polars is simple and intuitive using the str namespace functions combined with alias(). For example, if you want to convert all course names to uppercase and save the result in a new column named "Course_Upper", you can do it like this.

    
    # Convert strings to uppercase and alias the expression
    course_upper_expr = pl.col("Courses").str.to_uppercase().alias("Course_Upper")
    
    # Select original and manipulated column
    result = df.select([
        pl.col("Courses"),
        course_upper_expr
    ])
    print(result)
    
    # Output:
    # shape: (4, 2)
    ┌─────────┬──────────────┐
    │ Courses ┆ Course_Upper │
    │ ---     ┆ ---          │
    │ str     ┆ str          │
    ╞═════════╪══════════════╡
    │ Spark   ┆ SPARK        │
    │ Hadoop  ┆ HADOOP       │
    │ Python  ┆ PYTHON       │
    │ Pandas  ┆ PANDAS       │
    └─────────┴──────────────┘
    

    Here,

    <a id="h-concatenating-strings-with-alias"></a>

    Concatenating Strings with Alias

    To concatenate strings in Polars and assign a custom name to the result, you can use pl.concat_str() along with alias(). For example, if you want to create a new column called "Full_Course_Name" by combining the values in the Courses column with the word "Course" (e.g., "Spark Course", "Hadoop Course"), you can do it like this.

    
    # Concatenate strings and use alias
    df2 = df.with_columns(
        pl.concat_str([pl.col("Courses"), pl.lit(" Course")]).alias("Full_Course_Name")
    )
    print(df2)
    
    # Concatenate strings with alias
    result = df.select(
        pl.col("Courses"),
        (pl.col("Courses") + " Course").alias("Full_Course_Name")
    )
    print(result)
    
    # Output:
    # shape: (4, 4)
    ┌─────────┬───────┬──────────┬──────────────────┐
    │ Courses ┆ Fees  ┆ Discount ┆ Full_Course_Name │
    │ ---     ┆ ---   ┆ ---      ┆ ---              │
    │ str     ┆ i64   ┆ i64      ┆ str              │
    ╞═════════╪═══════╪══════════╪══════════════════╡
    │ Spark   ┆ 22000 ┆ 1000     ┆ Spark Course     │
    │ Hadoop  ┆ 25000 ┆ 1500     ┆ Hadoop Course    │
    │ Python  ┆ 20000 ┆ 1200     ┆ Python Course    │
    │ Pandas  ┆ 26000 ┆ 2500     ┆ Pandas Course    │
    └─────────┴───────┴──────────┴──────────────────┘
    

    Here,

    <a id="h-chaining-multiple-transformations-with-alias"></a>

    Chaining Multiple Transformations with Alias

    Chaining multiple transformations is both clean and efficient in Polars using with_columns() combined with method chaining. For example, create a new column "Final_Fee" by subtracting Discount from Fees, generate a string label "Course_Label" by concatenating the course name with "Course", convert course names to uppercase, and store them in "Course_Upper".

    
    df2 = df.with_columns([
        (pl.col("Fees") - pl.col("Discount")).alias("Final_Fee"),
        pl.concat_str([pl.col("Courses"), pl.lit(" Course")]).alias("Course_Label"),
        pl.col("Courses").str.to_uppercase().alias("Course_Upper")
    ])
    print(df2)
    
    # Output:
    # shape: (4, 6)
    ┌─────────┬───────┬──────────┬───────────┬───────────────┬──────────────┐
    │ Courses ┆ Fees  ┆ Discount ┆ Final_Fee ┆ Course_Label  ┆ Course_Upper │
    │ ---     ┆ ---   ┆ ---      ┆ ---       ┆ ---           ┆ ---          │
    │ str     ┆ i64   ┆ i64      ┆ i64       ┆ str           ┆ str          │
    ╞═════════╪═══════╪══════════╪═══════════╪═══════════════╪══════════════╡
    │ Spark   ┆ 22000 ┆ 1000     ┆ 21000     ┆ Spark Course  ┆ SPARK        │
    │ Hadoop  ┆ 25000 ┆ 1500     ┆ 23500     ┆ Hadoop Course ┆ HADOOP       │
    │ Python  ┆ 20000 ┆ 1200     ┆ 18800     ┆ Python Course ┆ PYTHON       │
    │ Pandas  ┆ 26000 ┆ 2500     ┆ 23500     ┆ Pandas Course ┆ PANDAS       │
    └─────────┴───────┴──────────┴───────────┴───────────────┴──────────────┘
    

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

    Conclusion

    In summary, Polars provides a flexible and efficient way to manipulate data with features like aliasing, string functions, and method chaining. These tools help you write clean, readable, and powerful data transformation pipelines with ease.

    Happy Learning!!

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

    Related Articles

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

    Reference