Pandas 创建只有列名的空 DataFrame - Pandas create empty DataFrame with only column names

10/14 02:37
阅读数 0

问题:

I have a dynamic DataFrame which works fine, but when there are no data to be added into the DataFrame I get an error.我有一个可以正常工作的动态 DataFrame,但是当没有要添加到 DataFrame 中的数据时,我收到错误消息。 And therefore I need a solution to create an empty DataFrame with only the column names.因此,我需要一个解决方案来创建一个只有列名的空 DataFrame。

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. PS:列名仍会出现在 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:我发现了一件重要的事情:我正在使用 Jinja2 将此 DataFrame 转换为 PDF,因此我调用了一种方法来首先将其输出为 HTML,如下所示:

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 . Edit2:一般来说,我遵循这个例子: http : //pbpython.com/pdf-reports.html The css is also from the link. css 也来自链接。 That's what I do to send the dataframe to the PDF:这就是我将数据框发送到 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:编辑3:

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:这似乎很合理,但如果我打印出 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: E4:如果我打印出以下内容:

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>

解决方案:

参考一: https://en.stackoom.com/question/30m3W
参考二: https://stackoom.com/question/30m3W
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部