Built with Tutify.io

    AIStudyLabs

    How to Append a Python List to Another List (Series) of a Polars DataFrame?

    How to Append a Python List to Another List (Series) of a Polars DataFrame?

    To append a Python list to each list in a column of a Polars DataFrame, you can use the list.concat() method. This method efficiently merges the existing list values in each row with the new list you wish to add.

    Appending a Python list to another list (Series) in a Polars DataFrame involves adding new elements to the existing list values within a column. In this article, I’ll walk you through how to perform this operation effectively using Polars.

    Key Points –

    <a id="h-usage-of-append-a-python-list-to-another-list-series"></a>

    Usage of Append a Python List to Another List (Series)

    You can append a Python list to another list (Series) within a polars DataFrame column using the list.concat() method. This allows you to combine or extend lists that are already present in a column, making it easier to work with nested data structures or dynamic lists.

    First, let’s create a Polars DataFrame.

    
    import polars as pl
    
    # Create a DataFrame with a list column
    df = pl.DataFrame({
        "values": [[5, 10,], [15, 20], [25, 30]]
    })
    print("Original DataFrame:\n", df)
    

    Yields below output.

    To append integers to a list column in a Polars DataFrame, you can use the list.concat() function, which concatenates lists in the DataFrame with the given integer values.

    
    # Append integers to the list column (e.g., append [35, 40] to each list)
    df2 = df.with_columns(pl.col("values").list.concat([pl.lit([35, 40])]))
    print("After appending integers to the list column:\n", df2)
    
    # Append integers to the list column 
    df2 = df.with_columns(pl.col("values").list.concat([35, 40]))
    print("After appending integers to the list column:\n", df2)
    

    Here,

    <a id="h-append-a-single-element-list"></a>

    Append a Single-Element List

    To append a single-element list to a list column in a Polars DataFrame, you can follow a similar approach using list.concat() with a single-element list. Here’s how you can append a single-element list (e.g., [50]) to each list in the values column.

    
    # Append a single-element list (e.g., [50]) to each list in the "values" column
    df2 = df.with_columns(pl.col("values").list.concat([pl.lit([50])]))
    print("DataFrame after appending a single-element list to the list column:\n", df2)
    
    # Output:
    # DataFrame after appending a single-element list to the list column:
    # shape: (3, 1)
    ┌──────────────┐
    │ values       │
    │ ---          │
    │ list[i64]    │
    ╞══════════════╡
    │ [5, 10, 50]  │
    │ [15, 20, 50] │
    │ [25, 30, 50] │
    └──────────────┘
    

    Here,

    <a id="h-append-to-empty-lists"></a>

    Append to Empty Lists

    To append to empty lists in a Polars DataFrame, you can use the list.concat() method, even if the lists are initially empty. Here's how you can append a list (e.g., [10, 20]) to each empty list in the values column.

    
    import polars as pl
    
    # Create a DataFrame with empty lists in the column
    df = pl.DataFrame({
        "values": [[], [], []]  # Empty lists in each row
    })
    
    # Append a list (e.g., [10, 20]) to each empty list
    df2 = df.with_columns(pl.col("values").list.concat([pl.lit([10, 20])]))
    print("DataFrame after appending to empty lists:\n", df2)
    
    # Output:
    # DataFrame after appending to empty lists:
    # shape: (3, 1)
    ┌───────────┐
    │ values    │
    │ ---       │
    │ list[i64] │
    ╞═══════════╡
    │ [10, 20]  │
    │ [10, 20]  │
    │ [10, 20]  │
    └───────────┘
    

    Here,

    <a id="h-append-a-list-of-booleans"></a>

    Append a List of Booleans

    To append a list of booleans to a list column in a Polars DataFrame, you can use the list.concat() method, similar to appending any other type of list. Here's an example where we append a boolean list (e.g., [True, False]) to each list in the values column.

    
    import polars as pl
    
    df = pl.DataFrame({"values": [[True], [False]]})
    
    df2 = df.with_columns(pl.col("values").list.concat([pl.lit([True, False])]))
    print("DataFrame after appending a list of booleans to the list column:\n", df2)
    
    # Output:
    # DataFrame after appending a list of booleans to the list column:
    # shape: (2, 1)
    ┌──────────────────────┐
    │ values               │
    │ ---                  │
    │ list[bool]           │
    ╞══════════════════════╡
    │ [true, true, false]  │
    │ [false, true, false] │
    └──────────────────────┘
    

    Here,

    <a id="h-append-dynamic-list-stored-in-a-variable"></a>

    Append Dynamic List Stored in a Variable

    To append a dynamic list stored in a variable to a list column in a Polars DataFrame, simply pass the variable directly into the list.concat() method.

    
    import polars as pl
    
    # Create a DataFrame with a list column
    df = pl.DataFrame({
        "values": [[1, 2], [3, 4], [5, 6]]
    })
    
    # Define a dynamic list to append
    dynamic_list = [7, 8]
    
    # Append the dynamic list to each list in the "values" column
    df2 = df.with_columns(pl.col("values").list.concat([pl.lit(dynamic_list)]))
    print("DataFrame after appending the dynamic list to the list column:\n", df2)
    
    # Output:
    # DataFrame after appending the dynamic list to the list column:
    # shape: (3, 1)
    ┌─────────────┐
    │ values      │
    │ ---         │
    │ list[i64]   │
    ╞═════════════╡
    │ [1, 2, … 8] │
    │ [3, 4, … 8] │
    │ [5, 6, … 8] │
    └─────────────┘
    

    Here,

    <a id="h-append-strings-to-list-column"></a>

    Append Strings to List Column

    To append strings to a list column in a Polars DataFrame, you can use the list.concat() method just like with numeric or boolean lists.

    
    import polars as pl
    
    # Create a DataFrame with string lists
    df = pl.DataFrame({
        "Tech": [["Spark"], ["Pandas", "Pyspark"], ["Polars"]]
    })
    
    # Define the string list to append
    extra_words = ["Hadoop", "C"]
    
    # Append the string list to each list in the "words" column
    df2 = df.with_columns(
        pl.col("Tech").list.concat([pl.lit(extra_words)]))
    print("DataFrame after appending strings to the list column:\n", df2)
    
    # Output:
    # DataFrame after appending strings to the list column:
    # shape: (3, 1)
    ┌──────────────────────────────┐
    │ Tech                         │
    │ ---                          │
    │ list[str]                    │
    ╞══════════════════════════════╡
    │ ["Spark", "Hadoop", "C"]     │
    │ ["Pandas", "Pyspark", … "C"] │
    │ ["Polars", "Hadoop", "C"]    │
    └──────────────────────────────┘
    

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

    Conclusion

    In summary, appending a Python list to a list column in a Polars DataFrame is both simple and efficient with the list.concat() method. Whether you're dealing with integers, booleans, empty lists, or lists stored in variables, Polars offers a flexible and robust solution for managing nested list data.

    Happy Learning!!

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

    Related Articles

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

    Reference