Search code examples
pythondataframeseriespython-polars

How can I convert a Polars Dataframe to a Python list


I understand Polars Series can be exported to a Python list. However, is there any way I can convert a Polars Dataframe to a Python list?

In addition, if there is a one single column in the Polars Dataframe, how can I convert that into a Polars Series?

I tried to use the pandas commands but it didn't work. I also checked the official Polars website to see any related built-in functions, but I didn't see any.


Solution

  • How about the rows() method?

    df = pl.DataFrame(
        {
            "a": [1, 3, 5],
            "b": [2, 4, 6],
        }
    )
    
    df.rows()
    

    [(1, 2), (3, 4), (5, 6)]

    df.rows(named=True)
    

    [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}]

    Alternatively, you could get all the DataFrame's columns using the get_columns() method, which would give you a list of Series, which you can then convert into a list of lists using the to_list() method on each Series in the list.

    If that's not what you're looking for be sure to hit me up with a reply, maybe then I'll be able to be of help to you.