Create a Polars Dataframe by appending multiple row at a time

2.6k views Asked by At

How can I make DataFrame and then more rows one at a time?

import polars as pl


df_polars = pl.DataFrame({
    'abc': [],
    'def': [],
    'ghi': []
})


value_to_set = 10.0
df_polars = df_polars.extend([
    pl.lit(None).alias('abc'),   
    pl.lit(value_to_set).alias('def'),
    pl.lit(None).alias('ghi')  
])


print(df_polars)

It only works for one field at a time. What is a more efficient approach to add several rows to my data-frame?

1

There are 1 answers

1
Ömer Sezer On

Brainstorming idea => adding a list of the dictionary, converting to DF, and concatenating:

new_rows = [{'abc': None, 'def': value, 'ghi': None} for value in values_to_set]  # list of the dictionary
new_df = pl.DataFrame(new_rows)                             # new DataFrame with the new rows
df_polars = pl.concat([df_polars, new_df])                  # Concatenate