Create Empty Dataframe in Pandas specifying column types

前端 未结 11 1957
萌比男神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:46

    This really smells like a bug.

    Here's another (simpler) solution.

    import pandas as pd
    import numpy as np
    
    def df_empty(columns, dtypes, index=None):
        assert len(columns)==len(dtypes)
        df = pd.DataFrame(index=index)
        for c,d in zip(columns, dtypes):
            df[c] = pd.Series(dtype=d)
        return df
    
    df = df_empty(['a', 'b'], dtypes=[np.int64, np.int64])
    print(list(df.dtypes)) # int64, int64
    

提交回复
热议问题