Elegant way to create empty pandas DataFrame with NaN of type float
Simply pass the desired value as first argument, like 0
, math.inf
or, here, np.nan
. The constructor then initializes and fills the value array to the size specified by arguments index
and columns
:
>>> import numpy as np>>> import pandas as pd>>> df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])>>> df A B0 NaN NaN1 NaN NaN2 NaN NaN3 NaN NaN>>> df.dtypesA float64B float64dtype: object
You could specify the dtype directly when constructing the DataFrame:
>>> df = pd.DataFrame(index=range(0,4),columns=['A'], dtype='float')>>> df.dtypesA float64dtype: object
Specifying the dtype forces Pandas to try creating the DataFrame with that type, rather than trying to infer it.