熊猫仅使用列名创建空的DataFrame

问题:熊猫仅使用列名创建空的DataFrame

我有一个动态的DataFrame,它工作正常,但是当没有数据要添加到DataFrame中时,出现错误。因此,我需要一个解决方案以仅使用列名创建一个空的DataFrame。

现在我有这样的事情:

df = pd.DataFrame(columns=COLUMN_NAMES) # Note that there are now row data inserted.

PS:重要的是,列名仍应出现在DataFrame中。

但是当我这样使用它时,我得到的结果是这样的:

Index([], dtype='object')
Empty DataFrame

“空DataFrame”部分很好!但是,除了索引之外,我还需要显示列。

编辑:

我发现的一件重要事情:我正在使用Jinja2将此DataFrame转换为PDF,因此我在调出一种方法,首先将其输出为HTML,如下所示:

df.to_html()

我认为这是专栏迷路的地方。

Edit2:通常,我遵循以下示例:http : //pbpython.com/pdf-reports.html。CSS也来自链接。这就是我将数据帧发送到PDF的过程:

env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("pdf_report_template.html")
template_vars = {"my_dataframe": df.to_html()}

html_out = template.render(template_vars)
HTML(string=html_out).write_pdf("my_pdf.pdf", stylesheets=["pdf_report_style.css"])

编辑3:

如果在创建后立即打印出数据框,则会得到以下信息:

[0 rows x 9 columns]
Empty DataFrame
Columns: [column_a, column_b, column_c, column_d, 
column_e, column_f, column_g, 
column_h, column_i]
Index: []

这似乎是合理的,但是如果我打印出template_vars:

'my_dataframe': '<table border="1" class="dataframe">\n  <tbody>\n    <tr>\n      <td>Index([], dtype=\'object\')</td>\n      <td>Empty DataFrame</td>\n    </tr>\n  </tbody>\n</table>'

似乎这些列已经丢失了。

E4:如果我打印出以下内容:

print(df.to_html())

我已经得到以下结果:

<table border="1" class="dataframe">
  <tbody>
    <tr>
      <td>Index([], dtype='object')</td>
      <td>Empty DataFrame</td>
    </tr>
  </tbody>
</table>

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 DataFrame with only the column names.

For now I have something like this:

df = pd.DataFrame(columns=COLUMN_NAMES) # Note that there are now row data inserted.

PS: It is important that the column names would still appear in a DataFrame.

But when I use it like this I get something like that as a result:

Index([], dtype='object')
Empty DataFrame

The “Empty DataFrame” part is good! But instead of the Index thing I need to still display the columns.

Edit:

An important thing that I found out: I am converting this DataFrame to a PDF using Jinja2, so therefore I’m calling out a method to first output it to HTML like that:

df.to_html()

This is where the columns get lost I think.

Edit2: In general, I followed this example: http://pbpython.com/pdf-reports.html. The css is also from the link. That’s what I do to send the dataframe to the PDF:

env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("pdf_report_template.html")
template_vars = {"my_dataframe": df.to_html()}

html_out = template.render(template_vars)
HTML(string=html_out).write_pdf("my_pdf.pdf", stylesheets=["pdf_report_style.css"])

Edit3:

If I print out the dataframe right after creation I get the followin:

[0 rows x 9 columns]
Empty DataFrame
Columns: [column_a, column_b, column_c, column_d, 
column_e, column_f, column_g, 
column_h, column_i]
Index: []

That seems reasonable, but if I print out the template_vars:

'my_dataframe': '<table border="1" class="dataframe">\n  <tbody>\n    <tr>\n      <td>Index([], dtype=\'object\')</td>\n      <td>Empty DataFrame</td>\n    </tr>\n  </tbody>\n</table>'

And it seems that the columns are missing already.

E4: If I print out the following:

print(df.to_html())

I get the following result already:

<table border="1" class="dataframe">
  <tbody>
    <tr>
      <td>Index([], dtype='object')</td>
      <td>Empty DataFrame</td>
    </tr>
  </tbody>
</table>

回答 0

您可以使用列名称或索引创建一个空的DataFrame:

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: []

要么

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]

编辑:即使您对.to_html进行了修改,我也无法复制。这个:

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

生成:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

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:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

回答 1

您是否正在寻找这样的东西?

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

   Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')

Are you looking for something like this?

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

   Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')

回答 2

df.to_html() 有一个columns参数。

只需将列传递到to_html()方法中即可。

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

df.to_html() has a columns parameter.

Just pass the columns into the to_html() method.

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