Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append items within a list to Polars Daraframe

I would like to append or concatenate horizontally list of items to Polars based daraframe through for loop.

In pandas –

import polars as pl
import pandas as pd
import numpy as np 

add_list = [(10, 100, 'd'), (20, 20, 'D')]

df1_pd = pd.DataFrame({ "a": [1, 2, 3], "b": [6, 7, 8], "c": ["a", "b", "c"]})

for d in add_list:
    ser_pd = pd.Series(data=d, index=df1_pd.columns)
    df1_pd = pd.concat([df1_pd, ser_pd.to_frame().T], ignore_index=True)

Gives desired output –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

How to achieve the same in polars?

df2_pl = pl.DataFrame({ "a": [1, 2, 3], "b": [6, 7, 8], "c": ["a", "b", "c"]})

for d in add_list:
    ser_pl = pl.Series(values=d, dtype=pl.Object)
    # next ??

**Solution (for the sake of completeness) –

for d in add_list:
    arr = np.asarray(d).reshape(-1, len(d))
    df2_pl = pl.concat([df2_pl, pl.DataFrame(arr, schema=df2_pl.schema)])

>Solution :

I’d suggest not using a for-loop here, this is the kind of pattern why append was deprecated in pandas

You can do:

In [7]: pl.concat([df2_pl, pl.DataFrame(add_list, schema=df2_pl.schema)])
Out[7]:
shape: (5, 3)
┌─────┬─────┬─────┐
│ a   ┆ b   ┆ c   │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1   ┆ 6   ┆ a   │
│ 2   ┆ 7   ┆ b   │
│ 3   ┆ 8   ┆ c   │
│ 10  ┆ 100 ┆ d   │
│ 20  ┆ 20  ┆ D   │
└─────┴─────┴─────┘
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading