date | sku | quantity | unit price |
---|---|---|---|
datetime[μs] | str | i64 | f64 |
2014-07-10 17:09:39 | "ZC-07383" | 2 | 70.66 |
2013-12-21 23:59:55 | "LK-02338" | 8 | 43.46 |
2013-11-21 08:08:36 | "QS-76400" | 18 | 97.45 |
2014-06-08 01:33:20 | "FT-50146" | 20 | 66.51 |
2013-11-16 05:08:39 | "XX-25746" | 19 | 62.62 |
Retrieving a schema from a table in polars
collect_schema
100DaysOfPolars
In addition to showing column data types in the dataframe, Polars allows you to get a dictionary of data types where the key is the column name and the value is the data type. This is especially helpful when you’re writing data to a database and want the schema to be maintained. Below is a dataframe with various data types.
shape: (5, 4)
Get data types as dictionary
To get the data types as a dictionary, you can use the Polars method collect_schema
. Here’s how to do it:
print(df
.collect_schema() )
Schema({'date': Datetime(time_unit='us', time_zone=None), 'sku': String, 'quantity': Int64, 'unit price': Float64})
Get names, keys from schema
The schema dictionary has properties that you can access. For instance, if you only want the table column names from the schema, you can get them like this:
(df
.collect_schema()
.names() )
['date', 'sku', 'quantity', 'unit price']
Or, if you want the data types, you can get them like this:
(df
.collect_schema()
.keys() )
odict_keys(['date', 'sku', 'quantity', 'unit price'])
My Polars course is accepting enrollments. I can’t wait to teach you!