Hướng dẫn pandas styler to html - pandas Styler sang html
Phần này thể hiện trực quan hóa dữ liệu bảng bằng cách sử dụng lớp Styler. Để biết thông tin về trực quan hóa với biểu đồ, vui lòng xem trực quan biểu đồ. Tài liệu này được viết dưới dạng máy tính xách tay Jupyter và có thể được xem hoặc tải xuống tại đây.Styler class. For information on visualization with charting please see Chart Visualization. This document is written as a Jupyter Notebook, and can be viewed or downloaded here. Show
Đối tượng Styler và HTML#Kiểu dáng nên được thực hiện sau khi dữ liệu trong một khung dữ liệu đã được xử lý. Nhà tạo mẫu tạo ra một HTML s.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False)6 và tận dụng ngôn ngữ tạo kiểu CSS để thao tác nhiều tham số bao gồm màu sắc, phông chữ, biên giới, nền, v.v. Xem ở đây để biết thêm thông tin về các bảng HTML kiểu dáng. Điều này cho phép rất nhiều sự linh hoạt ra khỏi hộp và thậm chí cho phép các nhà phát triển web tích hợp DataFrames vào các thiết kế giao diện người dùng thoát của họ.Styler creates an HTML s.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False)6 and leverages CSS styling language to manipulate many parameters including colors, fonts, borders, background, etc. See here for more information on styling HTML tables. This allows a lot of flexibility out of the box, and even enables web developers to integrate DataFrames into their exiting user interface designs. Thuộc tính s.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False)7 là một thuộc tính trả về một đối tượng Styler. Nó có một phương thức s.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False)8 được xác định trên đó để chúng được hiển thị tự động trong sổ ghi chép Jupyter.Styler object. It has a s.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False)8 method defined on it so they are rendered automatically in Jupyter Notebook. import pandas as pd import numpy as np import matplotlib as mpl df = pd.DataFrame([[38.0, 2.0, 18.0, 22.0, 21, np.nan],[19, 439, 6, 452, 226,232]], index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)'], name='Actual Label:'), columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression', 'Random'],['Tumour', 'Non-Tumour']], names=['Model:', 'Predicted:'])) df.style
Đầu ra ở trên trông rất giống với biểu diễn HTML DataFrame tiêu chuẩn. Nhưng HTML ở đây đã gắn một số lớp CSS vào mỗi ô, ngay cả khi chúng tôi chưa tạo ra bất kỳ phong cách nào. Chúng ta có thể xem chúng bằng cách gọi phương thức .to_html (), trả về HTML RAW dưới dạng chuỗi, rất hữu ích để xử lý hoặc thêm vào một tệp - đọc thêm về CSS và HTML. Dưới đây chúng tôi sẽ chỉ ra cách chúng tôi có thể sử dụng chúng để định dạng DataFrame để giao tiếp nhiều hơn. Ví dụ: làm thế nào chúng ta có thể xây dựng s.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False)9:.to_html() method, which returns the raw HTML as string, which is useful for further processing or adding to a file - read on in More about CSS and HTML. Below we will show how we can use these to format the DataFrame to be more communicative. For example how we can build s.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False)9: Ma trận nhầm lẫn cho nhiều mô hình dự đoán ung thư.
Đầu ra ở trên trông rất giống với biểu diễn HTML DataFrame tiêu chuẩn. Nhưng HTML ở đây đã gắn một số lớp CSS vào mỗi ô, ngay cả khi chúng tôi chưa tạo ra bất kỳ phong cách nào. Chúng ta có thể xem chúng bằng cách gọi phương thức .to_html (), trả về HTML RAW dưới dạng chuỗi, rất hữu ích để xử lý hoặc thêm vào một tệp - đọc thêm về CSS và HTML. Dưới đây chúng tôi sẽ chỉ ra cách chúng tôi có thể sử dụng chúng để định dạng DataFrame để giao tiếp nhiều hơn. Ví dụ: làm thế nào chúng ta có thể xây dựng s.set_table_styles([ {'selector': 'th.col_heading', 'props': 'text-align: center;'}, {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'}, {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'}, ], overwrite=False) 9:Ma trận nhầm lẫn cho nhiều mô hình dự đoán ung thư.& nbsp;Styler can distinguish the display value from the actual value, in both datavalues and index or columns headers. To control the display value, the text is printed in each cell as string, and we can use the .format() and .format_index() methods to manipulate this according to a format spec string or a callable that takes a single value and returns a string. It is possible to define this for the whole table, or index, or for individual columns, or MultiIndex levels. Định dạng màn hình#precision argument to specifically help formatting floats, as well as decimal and thousands separators to support other locales, an na_rep argument to display missing data, and an escape argument to help displaying safe-HTML or safe-LaTeX. The default formatter is configured to adopt pandas’ s.set_table_styles({ ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'}, {'selector': 'td', 'props': 'border-left: 1px solid #000066'}] }, overwrite=False, axis=0)0 option, controllable using s.set_table_styles({ ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'}, {'selector': 'td', 'props': 'border-left: 1px solid #000066'}] }, overwrite=False, axis=0)1 df.style.format(precision=0, na_rep='MISSING', thousands=" ", formatter={('Decision Tree', 'Tumour'): "{:.2f}", ('Regression', 'Non-Tumour'): lambda x: "$ {:,.1f}".format(x*-1e6) })
Ma trận nhầm lẫn cho nhiều mô hình dự đoán ung thư. weather_df = pd.DataFrame(np.random.rand(10,2)*5, index=pd.date_range(start="2021-01-01", periods=10), columns=["Tokyo", "Beijing"]) def rain_condition(v): if v < 1.75: return "Dry" elif v < 2.75: return "Rain" return "Heavy Rain" def make_pretty(styler): styler.set_caption("Weather Conditions") styler.format(rain_condition) styler.format_index(lambda v: v.strftime("%A")) styler.background_gradient(axis=None, vmin=1, vmax=5, cmap="YlGnBu") return styler weather_df
weather_df.loc["2021-01-04":"2021-01-08"].style.pipe(make_pretty) Định dạng giá trị#
CÒN THIẾU$ -452 000 000.0 Sử dụng styler để thao tác với màn hình là một tính năng hữu ích vì việc duy trì việc lập chỉ mục và datavalues cho các mục đích khác giúp kiểm soát nhiều hơn. Bạn không phải ghi đè lên DataFrame của mình để hiển thị nó theo cách bạn muốn. Dưới đây là một ví dụ về việc sử dụng các hàm định dạng trong khi vẫn dựa vào dữ liệu cơ bản để lập chỉ mục và tính toán..hide() without any arguments, which might be useful if your index is integer based. Similarly column headers can be hidden by calling .hide(axis=“columns”) without any further arguments. Tokyo.hide() method and passing in a row/column label, a list-like or a slice of row/column labels to for the s.set_table_styles({ ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'}, {'selector': 'td', 'props': 'border-left: 1px solid #000066'}] }, overwrite=False, axis=0)2 argument. Hiding không thay đổi sự sắp xếp số nguyên của các lớp CSS, ví dụ: & NBSP; ẩn hai cột đầu tiên của DataFrame có nghĩa là lập chỉ mục lớp cột vẫn sẽ bắt đầu ở s.set_table_styles({ ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'}, {'selector': 'td', 'props': 'border-left: 1px solid #000066'}] }, overwrite=False, axis=0)3, vì s.set_table_styles({ ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'}, {'selector': 'td', 'props': 'border-left: 1px solid #000066'}] }, overwrite=False, axis=0)4 và s.set_table_styles({ ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'}, {'selector': 'td', 'props': 'border-left: 1px solid #000066'}] }, overwrite=False, axis=0)5 chỉ đơn giản bị bỏ qua. Chúng tôi có thể cập nhật đối tượng s.set_table_styles({ ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'}, {'selector': 'td', 'props': 'border-left: 1px solid #000066'}] }, overwrite=False, axis=0)6 của chúng tôi từ trước để ẩn một số dữ liệu và định dạng các giá trị. s = df.style.format('{:.0f}').hide([('Random', 'Tumour'), ('Random', 'Non-Tumour')], axis="columns") s
Các phương thức để thêm kiểu#Có 3 phương pháp chính để thêm các kiểu CSS tùy chỉnh vào Styler:3 primary methods of adding custom CSS styles to Styler:
Kiểu bảng#Kiểu bảng đủ linh hoạt để kiểm soát tất cả các phần riêng lẻ của bảng, bao gồm các tiêu đề và chỉ mục cột. Tuy nhiên, chúng có thể khó sử dụng để gõ cho các ô dữ liệu riêng lẻ hoặc cho bất kỳ loại định dạng có điều kiện nào, vì vậy chúng tôi khuyên bạn nên sử dụng các kiểu bảng được sử dụng để tạo kiểu rộng, chẳng hạn như toàn bộ hàng hoặc cột cùng một lúc. Các kiểu bảng cũng được sử dụng để kiểm soát các tính năng có thể áp dụng cho toàn bộ bảng cùng một lúc như tạo chức năng di chuột chung. Bộ chọn giả s.set_table_styles({ ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'}, {'selector': 'td', 'props': 'border-left: 1px solid #000066'}] }, overwrite=False, axis=0)7, cũng như các lựa chọn giả khác, chỉ có thể được sử dụng theo cách này. Để sao chép định dạng bình thường của các bộ chọn và thuộc tính CSS (cặp giá trị thuộc tính), ví dụ: tr:hover { background-color: #ffff99; } Định dạng cần thiết để chuyển các kiểu đến .set_table_styles () là một danh sách các dicts, mỗi loại có thẻ CSS-Selector và CSS-Properies. Các thuộc tính có thể là danh sách 2 bộ phận hoặc chuỗi CSS thông thường, ví dụ:.set_table_styles() is as a list of dicts, each with a CSS-selector tag and CSS-properties. Properties can either be a list of 2-tuples, or a regular CSS-string, for example: cell_hover = { # for row hover use |