Create Empty Dataframe in Pandas specifying column types

前端 未结 11 1981
萌比男神i
萌比男神i 2020-11-28 08:39

I\'m trying to create an empty data frame with an index and specify the column types. The way I am doing it is the following:

df = pd.DataFrame(index=[\'pbp\         


        
11条回答
  •  情书的邮戳
    2020-11-28 09:06

    Create Empty Dataframe in Pandas specifying column types

    I think this is perfect!!

    import pandas as pd
    
    c1 = pd.Series(data=None, dtype='string', name='c1')
    c2 = pd.Series(data=None, dtype='bool', name='c2')
    c3 = pd.Series(data=None, dtype='float', name='c3')
    c4 = pd.Series(data=None, dtype='int', name='c4')
    
    df = pd.concat([c1, c2, c3, c4], axis=1)
    
    df.info('verbose')
    

    We create columns as Series and give them the correct dtype, then we concat de Series into a DataFrame, and that's it

    We have the DataFrame constructor with dtypes!

    
    Index: 0 entries
    Data columns (total 4 columns):
     #   Column  Non-Null Count  Dtype  
    ---  ------  --------------  -----  
     0   c1      0 non-null      string 
     1   c2      0 non-null      bool   
     2   c3      0 non-null      float64
     3   c4      0 non-null      int32  
    dtypes: bool(1), float64(1), int32(1), string(1)
    memory usage: 0.0+ bytes
    

提交回复
热议问题