홈>
이것은 멍청한 질문으로 들릴지 모르지만, 파이썬이 최고의 언어 중 하나가 아니기 때문에 나는 그것에 갇혀 있습니다.
테이블이있는 html 페이지가 있고 그 안에 팬더 데이터 프레임을 표시하고 싶습니다. 가장 좋은 방법은 무엇입니까? pandasdataframe.to_html을 사용 하시겠습니까?
py
from flask import Flask;
import pandas as pd;
from pandas import DataFrame, read_csv;
file = r'C:\Users\myuser\Desktop\Test.csv'
df = pd.read_csv(file)
df.to_html(header="true", table_id="table")
html
<div class="table_entrances" style="overflow-x: auto;">
<table id="table">
<thead></thead>
<tr></tr>
</table>
</div>
- 답변 # 1
- 답변 # 2
# Declare table class SomeTable(Table): status = Col('Customer') city = Col('City') product_price = Col('Country') # Convert the pandas Dataframe into dictionary structure output_dict = output.to_dict(orient='records') # Populate the table table = SomeTable(output_dict) return (table.__html__())
또는 팬더가 정적 HTML 파일을 반환 할 때 Flask를 사용하여 페이지로 렌더링 할 수 있습니다
@app.route('/<string:filename>/') def render_static(filename): return render_template('%s.html' % filename)
플라스크에서 어떻게 할 수 있는지에 대한 아이디어입니다. 이 내용을 이해하고 도움이되지 않는 경우 알려 주시기 바랍니다.
업데이트 :import pandas as pd df = pd.DataFrame({'col1': ['abc', 'def', 'tre'], 'col2': ['foo', 'bar', 'stuff']}) from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return df.to_html(header="true", table_id="table") if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
하지만 스타일링으로 인해 DataFrame to HTML 대신 Flask HTML 기능을 사용합니다.
- 답변 # 3
누군가 도움이되는 경우를 대비하여. 작업을 수행하는 테이블에 버튼을 추가하는 기능을 포함하여 더 많은 사용자 정의가 필요했기 때문에 대안을 찾았습니다. 또한 표준 테이블 형식이 매우 추악하므로 IMHO가 마음에 들지 않습니다.
... df = pd.DataFrame({'Patient Name': ["Some name", "Another name"], "Patient ID": [123, 456], "Misc Data Point": [8, 53]}) ... # link_column is the column that I want to add a button to return render_template("patient_list.html", column_names=df.columns.values, row_data=list(df.values.tolist()), link_column="Patient ID", zip=zip)
HTML 코드 : 모든 DF를 사용자 정의 가능한 HTML 테이블로 동적으로 변환합니다
<table> <tr> {% for col in column_names %} <th>{{col}}</th> {% endfor %} </tr> {% for row in row_data %} <tr> {% for col, row_ in zip(column_names, row) %} {% if col == link_column %} <td> <button type="submit" value={{ row_ }} name="person_id" form="patient_form" class="patient_button"> {{ row_ }} </button> </td> {% else %} <td>{{row_}}</td> {% endif %} {% endfor %} </tr> {% endfor %} </table>
CSS 코드
table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; }
그것은 아주 잘 작동하며
.to_html
보다 더 잘 보입니다. - 답변 # 4
Jinja 's for loop를 사용하는 경우
{% for table in tables %} {{titles[loop.index]}} {{ table|safe }} {% endfor %}
각 문자를 1 씩 1 씩 인쇄했기 때문에 많은 작업이 필요했습니다.
{{ table|safe }}
관련 자료
- python 3.x - 데이터 프레임의 기존 값에 쉼표를 어떻게 추가 할 수 있습니까? 판다
- python - Pandas 데이터 프레임을 Column == value 열이있는 테이블로 변환하는 방법은 무엇입니까?
- python - Pandas 데이터 프레임의 모든 것을 SQL Server의 테이블에 어떻게 삽입 할 수 있습니까?
- python - Pandas Dataframe이 기존 행을 재정의합니다
- python - 팬더 데이터 프레임은 전체 열을 동일한 크기의 개체로 바꿉니다
- python - Pandas 데이터 프레임의 각 행을 복제하고 목록을 기반으로 일부 열의 값을 변경합니다
- python - pandas에서 다중 인덱스 데이터 프레임 녹이기
- python - Pandas 데이터 프레임을 datetime 및 범주로 리 바인딩
- python - 데이터 프레임을 필터링하고 한 번에 하위 집합을 만드는 방법 Pandas
- python - Pandas Groupby 및 피벗 테이블 플로팅
- 하이브 테이블에 Pyspark 데이터 프레임
- python - Pandas 교차 조인 데이터 프레임 및 시리즈
- python - pandas는 데이터 프레임을 pivot_table로 변환합니다 여기서 index는 정렬 값입니다
- java - Springboot Hibernate는 SQL Server의 기존 테이블에서 데이터를 읽습니다
- python 3.x - ipywidgets 출력에서 pandas 데이터 프레임을 반환하는 방법
- python - pandas Dataframe에서 size 함수를 사용하면서 그룹의 모든 열을 유지하는 방법
- python 3.x - pandas 데이터 프레임에서 특정 행 제거
- python - 학교를 통한 루프는 데이터 프레임 팬더에 추가됩니다
- python - DataFrame Pandas를 전치하고 새 열 추가
- python - Pandas 데이터 프레임의 모든 샘플에 지난 시간 평균 추가
관련 질문
- python : Pandas에서 조건을 만족하는 셀들을 하나의 셀로 결합하면서 컬럼명과 충족된 조건별로 그룹화하는 방법
- python : 파이썬 엑셀 데이터 추가
- python : 플라스크를 사용하여 heroku bert pytorch 모델에 배포: 오류: _pickle.UnpicklingError: 잘못된 로드 키, 'v'
- python : 큰 숫자가 PLOT Pandas에 나타나지 않도록 차단
- python : 'function' 개체에는 JSON에 'load' 속성이 없습니다.
- python : 히스토그램에 백분위수 값 표시 문제
- python : 행을 추가할 때 dtype이 object로 변경되는 이유는 무엇입니까?
- python : pandas resample에서 first()는 무엇을 합니까?
- python : 다른 목록에서 요소를 찾는 df 열(각 행이 목록인 경우)을 어떻게 반복합니까?
- python : 열에서 많은 열로 데이터 분할 및 생성
작업 예 :
파이썬 코드 :
html :
또는 다른 용도
와
{{titles[loop.index]}}
를 제거 html에서 줄html에서 요소를 검사하는 경우
알다시피 표 html에 tbody와 thead가 있습니다. CSS를 쉽게 적용 할 수 있습니다.