Am un DataFrame dinamic care funcționează bine, dar atunci când nu există date care să fie adăugate în DataFrame primesc o eroare. Și, prin urmare, am nevoie de o soluție pentru a crea un DataFrame gol cu doar numele coloanelor.
Deocamdată am ceva de genul acesta:
df = pd.DataFrame(columns=COLUMN_NAMES) # Note that there are now row data inserted.
PS: Este important ca numele coloanelor să apară în continuare într-un DataFrame.
Dar când îl folosesc astfel, obțin un rezultat de genul acesta:
Index([], dtype='object')
Empty DataFrame
Partea cu "Empty DataFrame" este bună! Dar, în loc de chestia cu Indexul, am nevoie să afișez în continuare coloanele.
Editați:
Un lucru important pe care l-am aflat: Eu convertesc acest DataFrame într-un PDF folosind Jinja2, așa că, prin urmare, chem o metodă pentru a ieși mai întâi în HTML:
df.to_html()
Cred că aici se pierd coloanele.
Editare2: În general, am urmat acest exemplu: http://pbpython.com/pdf-reports.html. Css-ul este, de asemenea, din link. Asta fac eu pentru a trimite dataframe-ul în 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"])
Editare3:
Dacă tipăresc dataframe-ul imediat după creare, obțin următoarele:
[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: []
Acest lucru pare rezonabil, dar dacă tipăresc 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>'
Și se pare că coloanele lipsesc deja.
E4: Dacă tipăresc următoarele:
print(df.to_html())
obțin deja următorul rezultat:
<table border="1" class="dataframe">
<tbody>
<tr>
<td>Index([], dtype='object')</td>
<td>Empty DataFrame</td>
</tr>
</tbody>
</table>
Puteți crea un DataFrame gol, fie cu nume de coloane, fie cu un 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: []
Sau
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]
Editați: Chiar și după amendamentul tău cu .to_html, nu pot să reproduc. Aceasta:
df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
df.to_html('test.html')
Produce:
<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>