Home > Article > Web Front-end > How to Change Cell Colors in a Pandas DataFrame HTML Table Using Styles and CSS?
Changing Cell Colors in a Pandas DataFrame HTML Table Using Styles and CSS
Question:
How can we customize the appearance of a pandas DataFrame HTML table by selectively coloring specific cells and headers?
Solution:
Utilizing pandas' new styling functionality, we can apply custom CSS rules to individual cells based on their row and column indices. To demonstrate:
Highlight MOS Rows:
Create a helper function that returns CSS styling based on whether the row corresponds to the 'MOS' header:
<code class="python">import pandas as pd def highlight_MOS(s): is_mos = s.index.get_level_values(1) == 'MOS' return ['color: darkorange' if v else 'color: darkblue' for v in is_mos]</code>
Apply CSS Styling:
Apply the styling function to the DataFrame using the apply() method:
<code class="python">s = df.style.apply(highlight_MOS)</code>
Display the Stylized Table:
The modified DataFrame will display the table with MOS rows highlighted in orange:
<code class="python">s</code>
Additional Customization:
This method allows further customization of the table's appearance through CSS. To change header and background colors, use the following properties in the CSS rules:
The above is the detailed content of How to Change Cell Colors in a Pandas DataFrame HTML Table Using Styles and CSS?. For more information, please follow other related articles on the PHP Chinese website!