我有一个动态的DataFrame,它工作得很好,但当没有数据要添加到DataFrame时,我得到一个错误。因此,我需要一个解决方案来创建一个只有列名的空DataFrame。

现在我有这样的东西:

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

PS:列名仍然会出现在DataFrame中,这很重要。

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

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

“空数据框架”部分很好!但我需要显示的不是索引,而是列。

我发现了一件重要的事情:我正在使用Jinja2将这个DataFrame转换为PDF,因此我调用了一个方法,首先将它输出到HTML,就像这样:

df.to_html()

我想这就是列的缺失之处。

总的来说,我遵循了这个例子: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"])

你在找这样的东西吗?

    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')

你可以创建一个空的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: []

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]

编辑: 即使你修改了。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>

Df.to_html()有一个columns形参。

只需将列传递给to_html()方法。

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

使用迭代创建colname

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()操作

print(df.to_html())

# <table border="1" class="dataframe">
#   <thead>
#     <tr style="text-align: right;">
#       <th></th>
#       <th>colname_0</th>
#       <th>colname_1</th>
#       <th>colname_2</th>
#       <th>colname_3</th>
#       <th>colname_4</th>
#     </tr>
#   </thead>
#   <tbody>
#   </tbody>
# </table>

这似乎有效

print(type(df.to_html()))
# <class 'str'>

这个问题是由

当你像这样生成df

df = pd.DataFrame(columns=COLUMN_NAMES)

它有0行× n列,您需要创建至少一行索引由

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

现在它有1行× n列。您可以添加数据。否则df只包含colnames对象(就像一个字符串列表)。

如果你有一个完全空的数据框架,没有列或索引,你可以通过给这些列赋值None来让它有列。

df = pd.DataFrame()                    # <---- shape: (0, 0)
df[['col1', 'col2', 'col3']] = None    # <---- shape: (0, 3)

然后为它分配一行,你可以使用loc索引器。这实际上可以在循环中用于添加更多行(这对于pd是不可取的。Concat的存在就是为了完成这个特定的任务)。

df.loc[len(df)] = ['abc', 10, 3.33]    # <---- shape: (1, 3)