Create Empty Dataframe in Pandas specifying column types

前端 未结 11 1937
萌比男神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 08:49

    pandas doesn't offer pure integer column. You can either use float column and convert that column to integer as needed or treat it like an object. What you are trying to implement is not the way pandas is supposed to be used. But if you REALLY REALLY want that, you can get around the TypeError message by doing this.

    df1 =  pd.DataFrame(index=['pbp'], columns=['str1','str2','str2'], dtype=str)
    df2 =  pd.DataFrame(index=['pbp'], columns=['int1','int2'], dtype=int)
    df3 =  pd.DataFrame(index=['pbp'], columns=['flt1','flt2'], dtype=float)
    df = pd.concat([df1, df2, df3], axis=1)
    
        str1 str2 str2 int1 int2  flt1  flt2
    pbp  NaN  NaN  NaN  NaN  NaN   NaN   NaN
    

    You can rearrange the col order as you like. But again, this is not the way pandas was supposed to be used.

     df.dtypes
    str1     object
    str2     object
    str2     object
    int1     object
    int2     object
    flt1    float64
    flt2    float64
    dtype: object
    

    Note that int is treated as object.

提交回复
热议问题