Home  >  Article  >  Web Front-end  >  How to Change Cell Colors in a Pandas DataFrame HTML Table Using Styles and CSS?

How to Change Cell Colors in a Pandas DataFrame HTML Table Using Styles and CSS?

DDD
DDDOriginal
2024-11-03 08:15:03413browse

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:

  1. 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>
  2. Apply CSS Styling:

    Apply the styling function to the DataFrame using the apply() method:

    <code class="python">s = df.style.apply(highlight_MOS)</code>
  3. 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:

  • background-color
  • color

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn