Pandas create empty DataFrame with only column names

后端 未结 4 1756
情歌与酒
情歌与酒 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:17

    You can create an empty DataFrame with either column names or an Index:

    In [4]: import pandas as pd
    In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
    In [6]: df
    Out[6]:
    Empty DataFrame
    Columns: [A, B, C, D, E, F, G]
    Index: []
    

    Or

    In [7]: df = pd.DataFrame(index=range(1,10))
    In [8]: df
    Out[8]:
    Empty DataFrame
    Columns: []
    Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Edit: Even after your amendment with the .to_html, I can't reproduce. This:

    df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
    df.to_html('test.html')
    

    Produces:

    A B C D E F G

提交回复
热议问题