Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a polars dataframe giving the colum-names from a list

I want to create a new polars dataframe from numpy arrays, so I want to add the column-names when creating the dataframe (as I do with pandas).

df = pl.DataFrame(noisy_data.tolist(), columns=[f"property_{i}" for i in range(num_columns)])

But polars does not like "columns"

TypeError: DataFrame.__init__() got an unexpected keyword argument 'columns'

In the Polats dataframe documentation I cannot see any parameter for defining the columns names

class polars.DataFrame(
  data: FrameInitTypes | None = None,
  schema: SchemaDefinition | None = None, 
  *,
  schema_overrides: SchemaDict | None = None,
  strict: bool = True,
  orient: Orientation | None = None,
  infer_schema_length: int | None = 100,
  nan_to_null: bool = False,
)

Another option is to rename the columns with a list of names after df creation.

like image 761
Pau Marin Avatar asked Sep 18 '25 11:09

Pau Marin


1 Answers

You should use schema, not columns as parameter to set up the column names in DataFrame:

df = pl.DataFrame(noisy_data.tolist(),
                  schema=[f'col_{i}' for i in range(num_columns)])

As described in the documentation:

schema: Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict

The schema of the resulting DataFrame. The schema may be declared in several ways:

  • As a dict of {name:type} pairs; if type is None, it will be auto-inferred.

  • As a list of column names; in this case types are automatically inferred.

  • As a list of (name,type) pairs; this is equivalent to the dictionary form.

If you supply a list of column names that does not match the names in the underlying data, the names given here will overwrite them. The number of names given in the schema should match the underlying data dimensions.

If set to None (default), the schema is inferred from the data.

like image 78
mozway Avatar answered Sep 21 '25 06:09

mozway