Pandas create empty DataFrame with only column names

后端 未结 4 1773
情歌与酒
情歌与酒 2021-01-29 18:38

I have a dynamic DataFrame which works fine, but when there are no data to be added into the DataFrame I get an error. And therefore I need a solution to create an empty DataFra

4条回答
  •  爱一瞬间的悲伤
    2021-01-29 19:11

    Creating colnames with iterating

    df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
    print(df)
    
    # Empty DataFrame
    # Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
    # Index: []
    

    to_html() operations

    print(df.to_html())
    
    # 
    #   
    #     
    #       
    #       
    #       
    #       
    #       
    #       
    #     
    #   
    #   
    #   
    # 
    colname_0colname_1colname_2colname_3colname_4

    this seems working

    print(type(df.to_html()))
    # 
    

    The problem is caused by

    when you create df like this

    df = pd.DataFrame(columns=COLUMN_NAMES)
    

    it has 0 rows × n columns, you need to create at least one row index by

    df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])
    

    now it has 1 rows × n columns. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).

提交回复
热议问题