Elegant way to create empty pandas DataFrame with NaN of type float

后端 未结 5 2171
轮回少年
轮回少年 2020-12-08 02:10

I want to create a Pandas DataFrame filled with NaNs. During my research I found an answer:

import pandas as pd

df = pd.DataFrame(index=range(0,4),columns=[         


        
5条回答
  •  情深已故
    2020-12-08 02:17

    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.dtypes
    A    float64
    B    float64
    dtype: object
    
    >>> df.values
    array([[nan, nan],
           [nan, nan],
           [nan, nan],
           [nan, nan]])
    

提交回复
热议问题