pythonpandasdataframepython-polarsrust-polars

How to initialise a polars dataframe with column names from database cursor description?


I'm connecting to Postgres Database using psycopg2 connector and using cursor property, i'm fetching the records along with their column names. Here is the code snippet of the same:

rds_conn = psycopg2.connect(
        host=config.RDS_HOST_NAME,
        database=config.RDS_DB_NAME,
        user=config.RDS_DB_USER,
        password=config.RDS_DB_PASSWORD,
        port=config.RDS_PORT)
    cur = rds_conn.cursor()
    cur.execute(sql_query)
    names = [x[0] for x in cur.description]
    rows = cur.fetchall()
    cur.close()

I'm initialising a Pandas dataframe with column names from the cursor.description property:

 df = pd.DataFrame(rows, columns=names)

Instead of Pandas dataframe, if i would like to initialise a Polars dataframe with column names from the cursor.description property, how would i do it? I don't want to convert Pandas to Polars dataframe.

I tried using polars.Dataframe.with_Columns property but it didn't work.

Can someone please help me on this?


Solution

  • You can pass the column names directly to the schema parameter of pl.DataFrame.

    import polars as pl
    
    names = ["a", "b", "c"]
    rows = [[0], [True], ["foo"]]
    
    pl.DataFrame(rows, schema=names)
    
    shape: (1, 3)
    ┌─────┬──────┬─────┐
    │ a   ┆ b    ┆ c   │
    │ --- ┆ ---  ┆ --- │
    │ i64 ┆ bool ┆ str │
    ╞═════╪══════╪═════╡
    │ 0   ┆ true ┆ foo │
    └─────┴──────┴─────┘