Home > OS >  how to convert an empty pandas Dataframe into a polars Dataframe
how to convert an empty pandas Dataframe into a polars Dataframe

Time:08-10

I have defined a pandas DataFrame as follows:

df_tmp = pd.DataFrame({'EDT': pd.Series(dtype='datetime64[ns]'),
                       'FSPB': pd.Series(dtype='str'),
                       'FS_LA': pd.Series(dtype='str'),
                       'lA': pd.Series(dtype='int'),
                       'avg': pd.Series(dtype='float64'),
                       'nw': pd.Series(dtype='float64')})

Is there any way to convert the above into an empty polars DataFrame?

CodePudding user response:

According to the polars docs, polars DataFrames can take a pandas DataFrame in their constructor, so:

import pandas as pd
import polars as pl

df_tmp = pd.DataFrame({'EDT': pd.Series(dtype='datetime64[ns]'),
                       'FSPB': pd.Series(dtype='str'),
                       'FS_LA': pd.Series(dtype='str'),
                       'lA': pd.Series(dtype='int'),
                       'avg': pd.Series(dtype='float64'),
                       'nw': pd.Series(dtype='float64')})

df = pl.DataFrame(df_tmp)

should work.

CodePudding user response:

import polars as pl
import pandas as pd

pandas_df = pd.DataFrame({'EDT': pd.Series(dtype='datetime64[ns]'),
                       'FSPB': pd.Series(dtype='str'),
                       'FS_LA': pd.Series(dtype='str'),
                       'lA': pd.Series(dtype='int'),
                       'avg': pd.Series(dtype='float64'),
                       'nw': pd.Series(dtype='float64')})

pl.from_pandas(pandas_df)
shape: (0, 6)
┌──────────────┬──────┬───────┬─────┬─────┬─────┐
│ EDT          ┆ FSPB ┆ FS_LA ┆ lA  ┆ avg ┆ nw  │
│ ---          ┆ ---  ┆ ---   ┆ --- ┆ --- ┆ --- │
│ datetime[ns] ┆ str  ┆ str   ┆ i64 ┆ f64 ┆ f64 │
╞══════════════╪══════╪═══════╪═════╪═════╪═════╡
└──────────────┴──────┴───────┴─────┴─────┴─────┘
  • Related