How can I convert a Polars Dataframe to a Python list
Asked Answered
M

2

7

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.

Miranda answered 21/2, 2023 at 19:57 Comment(1)
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.Rakeoff
S
16

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.

Sartor answered 22/2, 2023 at 3:33 Comment(0)
P
0

To convert a dataframe's column to a list:

import polars as pl

# data_df is a polars dataframe with a column named "values"
lst = pl.Series(data_df.select('values')).to_list()

To convert all columns of data_df to lists with names the same as the column names:

for name in data_df.columns:
    name = pl.Series(data_df.select(name)).to_list()
Putrid answered 6/8 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.