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

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

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

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.

>Solution :

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.

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