팬더는 열 이름만 사용하여 빈 데이터 프레임을 생성합니다.
다이나믹 데이터 프레임은 정상적으로 동작하고 있습니다만, 데이터 프레임에 추가할 데이터가 없으면 에러가 발생합니다.따라서 열 이름만으로 빈 Data Frame을 만드는 솔루션이 필요합니다.
지금으로서는 다음과 같은 것이 있습니다.
df = pd.DataFrame(columns=COLUMN_NAMES) # Note that there are now row data inserted.
PS: 데이터 프레임에 열 이름이 표시되는 것이 중요합니다.
하지만 이렇게 사용하면 다음과 같은 결과를 얻을 수 있습니다.
Index([], dtype='object')
Empty DataFrame
"빈 데이터 프레임" 부분이 좋습니다!그러나 인덱스 대신 열을 표시해야 합니다.
편집:
제가 알게 된 중요한 것은 이 Data Frame을 Jinja2를 사용하여 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>
열 이름 또는 인덱스를 사용하여 빈 데이터 프레임을 만들 수 있습니다.
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')
콜네임 작성iterating
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 rows × n columns
다음 방법으로 적어도1개의 행 인덱스를 작성해야 합니다.
df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])
지금은 가지고 있다1 rows × n columns
데이터를 추가할 수 있습니다.그 이외의 경우 df는 colnames 오브젝트(문자열 리스트 등)로만 구성됩니다.
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
'programing' 카테고리의 다른 글
요소에서 텍스트 선택(마우스로 강조 표시) (0) | 2022.11.27 |
---|---|
특정 길이까지 문자열 반복 (0) | 2022.11.07 |
PHP 추상 속성 (0) | 2022.11.07 |
Apache HttpClient 4.3의 SSL 인증서 무시 (0) | 2022.11.07 |
PHP 페이지 리다이렉트 (0) | 2022.11.07 |