Programing

Pandas는 열 이름만으로 빈 DataFrame을 만듭니다.

lottogame 2020. 8. 25. 19:20
반응형

Pandas는 열 이름만으로 빈 DataFrame을 만듭니다.


잘 작동하는 동적 DataFrame이 있지만 DataFrame에 추가 할 데이터가 없으면 오류가 발생합니다. 따라서 열 이름 만있는 빈 DataFrame을 만드는 솔루션이 필요합니다.

지금은 다음과 같습니다.

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

추신 : 열 이름이 DataFrame에 여전히 표시되는 것이 중요합니다.

그러나 이렇게 사용하면 결과적으로 다음과 같은 결과가 나타납니다.

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

"Empty DataFrame"부분이 좋습니다! 그러나 Index 대신에 여전히 열을 표시해야합니다.

편집하다:

내가 알아 낸 중요한 점 : 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>

열 이름 또는 인덱스를 사용하여 빈 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>

이와 같은 것을 찾고 있습니까?

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

df.to_html ()에는 열 매개 변수가 있습니다.

to_html () 메소드에 열을 전달하기 만하면됩니다.

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

참고URL : https://stackoverflow.com/questions/44513738/pandas-create-empty-dataframe-with-only-column-names

반응형