Try:

df = df.style.apply(lambda x: np.repeat('color: red' if x['error'] else '', x.shape[0]), axis=1)

When output to Excel it looks like...

Answer from MDR on Stack Overflow
🌐
GitHub
github.com β€Ί Textualize β€Ί rich
GitHub - Textualize/rich: Rich is a Python library for rich text and beautiful formatting in the terminal. Β· GitHub
You can also use the builtin Handler class to format and colorize output from Python's logging module. Here's an example of the output: ... To insert an emoji in to console output place the name between two colons. Here's an example: >>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") πŸ˜ƒ πŸ§› πŸ’© πŸ‘ 🦝 Β· Please use this feature wisely. ... Rich can render flexible tables with unicode box characters. There is a large variety of formatting options for borders, styles, cell ...
🌐
ZetCode
zetcode.com β€Ί python β€Ί rich
Python rich - how to create rich text & formatting in the terminal
In this article we create rich text and advanced formatting in the terminal using the Python rich library. The rich module allows us to add colours, emojis, tables, columns, or progress bars. We can do syntax highlighting, pretty printing.
Discussions

How do I make the categories have a coloured background when using the rich modules?
The documentation suggests setting the header_style option for each column when you add them. More on reddit.com
🌐 r/learnpython
4
2
February 14, 2024
python - changing value of every cell in dataframe to color the table - Stack Overflow
I took the same approach by adding ... the df cells, which also messed up resp. misaligned the printed dataframe. I also tried to insert rich color tags, which caused the same misalignment. Then I found this discussion on the pandas GitHub page about styling console/terminal output So, manipulating the dataframe for getting colors doesnΒ΄t seem to work. But the rich module was mentioned in the last post and I know you can create colorful tables with ... More on stackoverflow.com
🌐 stackoverflow.com
Is it possible to style a table with rows having alternating background colours?
Perhaps a picture is worth 1000 words: so as in https://datatables.net/examples/data_sources/dom.html I find it much easier to visually "track" rows with that alternating background colou... More on github.com
🌐 github.com
1
2
October 13, 2020
python - Set different background color using Rich - Stack Overflow
I found useful package rich. And want to use it in the next way: drawing in different colors words in sentence and at different background colors. I use next code: from rich.console import Console More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com β€Ί willmcgugan β€Ί rich β€Ί issues β€Ί 477
[REQUEST] Extend cell background color across entire row for a single row Β· Issue #477 Β· Textualize/rich
December 9, 2020 - V111: The Last Jedi", "$1,332,539,889", style="on green") table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889") console = Console() console.print(table) from rich.console import Console from rich.table import Table from rich import box row_styles=["", "", "on green", ""] #This is a bit messy...?
Author: Textualize
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί how do i make the categories have a coloured background when using the rich modules?
r/learnpython on Reddit: How do I make the categories have a coloured background when using the rich modules?
February 14, 2024 -

So I made this table and basically want the cell of each column's title to have a color program. How can I do this using the rich module (I'm using Replit rn)

from rich.console import Console #Allows for styling of text from rich.table import Table #For clear formatting and titles from colorama import Fore, Back, Style #To add colors

Info for each flight includng time, destination, airport code, flight #, terminal, carousel, and status

Title1 = Table(title="Arrivals for FEBRUARY 9, 2024\n") r2 = [[" 10:00","Regina","YQR","AC301","1","5","On Time"],
[" 12:00","Thunder Bay","YQT","AC452","2","7","Arrived"], [" 14:00","Winnipeg","YWG","AC326","3", "7","On Time"], [" 16:00","Ottawa","YOW","AC244","3","3","On Time"], [" 10:00","Yellowknife","YZF","AC521","1","8", "Arrived"], [" 12:00","PEI","YYG","AC403","2","4","On Time"], [" 14:00","Halifax","YHZ","AC322","1","2","Cancelled"], [" 16:00","Edmonton","YEG","AC208","4","1","On Time"], [" 10:00","Hamilton","YHM","AC333","1","6","Cancelled"], [" 12:00","Montreal","YUL","AC997","1","8","Delayed"], [" 14:00","Vancouver","YVR","AC654","3","2","Cancelled"], [" 16:00","Calgary","YYC","AC878","2","1","Arrived"]]

Title of categories (Bolded in white)

cat = ["ARRIVAL TIME","ARRIVING FROM","DESTINATION CODE","FLIGHT NUMBER"," TERMINAL", "CAROUSEL NUMBER"," STATUS",]

Each heading gets its own column

for column in cat: Title1.add_column(column)

Title2 = Table(title="\nDepartures for FEBRUARY 9, 2024\n")

r1 = [[" 10:30","Regina","YQR","AC321","1","3","On Time",], [" 13:00","Thunder Bay","YQT","AC665","2","1","Delayed"], [" 15:00","Winnipeg","YWG","AC332","3","5","On Time"], [" 17:00","Ottawa","YOW","AC244","3","5","On Time"], [" 11:00","Yellowknife","YZF","AC521","1","6","Arrived"], [" 15:00","PEI","YYG","AC403","2","4","On Time"], [" 17:00","Halifax","YHZ","AC451","1","5","Cancelled"], [" 17:00","Edmonton","YEG","AC909","4","1","On Time"], [" 18:00","Hamilton","YHM","AC313","1","7","Cancelled"], [" 19:00","Montreal","YUL","AC999","1","4","Delayed"], [" 21:00","Vancouver","YVR","AC623","3","5","Cancelled"], [" 23:00","Calgary","YYC","AC859","2","3","Delayed"]]

cat2 = ["DEPARTURE TIME","DESTINATION", "DESTINATION CODE","FLIGHT NUMBER"," TERMINAL","CAROUSEL NUMBER", " STATUS"]

Centers info to make it look nice

for i in r1: i[5] = i[5].center(15) i[4] = i[4].center(14) i[3] = i[3].center(14) i[2] = i[2].center(14)

for i in r2: i[5] = i[5].center(15) i[4] = i[4].center(14) i[3] = i[3].center(14) i[2] = i[2].center(14)

for column in cat2: Title2.add_column(column)

I begin coloring the text under the Status section according to the title using if, elif, and else statements

for row in r1: sy=row[6] if sy=="On Time": style='green' elif sy=="Cancelled": style='red' elif sy=="Arrived": style='blue' elif sy=="Delayed": style='yellow' else: style='white'

Adds styled rows

Title2.add_row(*row, style=style)

for row in r2: sy=row[6] if sy=="On Time": style='green' elif sy=="Cancelled": style='red' elif sy=="Arrived": style='blue' elif sy=="Delayed": style='yellow' else: style='white' Title1.add_row(*row, style=style)

Thanks for any help!

Top answer
1 of 2
2

Try:

df = df.style.apply(lambda x: np.repeat('color: red' if x['error'] else '', x.shape[0]), axis=1)

When output to Excel it looks like...

2 of 2
0

I wanted to do the same as CIsForCookies and color cells of a dataframe in a cmd console window. I took the same approach by adding colorama color tags to the df cells, which also messed up resp. misaligned the printed dataframe. I also tried to insert rich color tags, which caused the same misalignment.

Then I found this discussion on the pandas GitHub page about styling console/terminal output So, manipulating the dataframe for getting colors doesnΒ΄t seem to work.

But the rich module was mentioned in the last post and I know you can create colorful tables with it. So I tried pulling the last rows of my df to a json object, iterate through the json data and add colors where I need them and build a rich table out of this altered json data - and it worked :-)

Some code...

  1. Get the last 10 rows of df as an interable json data

    json_data = loads(df.tail(10).to_json(orient='index'))
  2. As an example, iterate through the json data and add green or red color background if the close is above or below the 20 EMA:

    for index in json_data: if json_data[index]['close'] >= json_data[index]['20EMA']: json_data[index]['20EMA'] = f"[black on green]{json_data[index]['20EMA']}[/]" else: json_data[index]['20EMA'] = f"[black on red]{json_data[index]['20EMA']}[/]"
  3. Create a rich table and add rows from the json data:

    for index in json_data: table.add_row(index, str(local_time), str(f"{json_data[index]['close']:.2f}"), str(int(json_data[index]['volume'])), str(json_data[index]['20EMA']), )

And finally, there you have a table from a df with different cell colors.

🌐
JCharisTech
blog.jcharistech.com β€Ί 2020 β€Ί 06 β€Ί 11 β€Ί rich-text-and-beautiful-formatting-in-the-terminal-with-rich-python
Rich Text and Beautiful Formatting in the Terminal with Rich Python – JCharisTech
June 11, 2020 - from rich.syntax import Syntax my_code = """ def hello(name): return "Hello {}".format(name) """ # Syntax synt = Syntax(my_code,"python",theme='monokai',line_numbers=True) console.print(synt) ... from rich.table import Table,Column table = Table(show_header=True,header_style="bold cyan") # Define Column table.add_column("Title",style="dim",width=12) table.add_column("Author",style="dim",width=12) # Add your Data into the Rows table.add_row("Python Handbook","Wes Mickn") console.print(table)
🌐
Rich
rich.readthedocs.io β€Ί en β€Ί stable β€Ί style.html
Styles β€” Rich 14.1.0 documentation
In various places in the Rich API you can set a β€œstyle” which defines the color of the text and various attributes such as bold, italic etc.
Find elsewhere
🌐
GitHub
github.com β€Ί Textualize β€Ί rich β€Ί blob β€Ί main β€Ί rich β€Ί table.py
rich/rich/table.py at main Β· Textualize/rich
Rich is a Python library for rich text and beautiful formatting in the terminal. - rich/rich/table.py at main Β· Textualize/rich
Author: Textualize
🌐
Salivity
salivity.github.io β€Ί python β€Ί article β€Ί python-rich-tables-syntax-and-progress-bars
Python Rich: Tables, Syntax, and Progress Bars - python
Granular Styling: Individual styles (color, bold, italic, dim) can be applied to entire columns, specific rows, individual cells, or headers and footers. Alignment and Padding: Columns can be aligned left, right, or centered, with custom horizontal and vertical padding. Nested Renderables: Table cells are not limited to plain text; they can contain other Rich elements, such as syntax blocks, progress bars, or nested tables.
🌐
Medium
medium.com β€Ί @alextrotman04 β€Ί enhance-your-cli-with-rich-python-tables-made-simple-6cdabbd59801
Enhance Your CLI with Rich: Python Tables Made Simple | by Alex Trotman | Medium
May 10, 2024 - The rich library isn't just another output formatter. It's a versatile and powerful tool that offers: Tables: Create beautiful tables with custom styles and layouts. Syntax Highlighting: Make code outputs more readable with colored syntax.
🌐
Reddit
reddit.com β€Ί r/python β€Ί python rich - my favorite way to add colors, emojis, tables and more...
r/Python on Reddit: Python Rich - My favorite way to add Colors, Emojis, Tables and More...
February 1, 2021 - Long time Python user here and I only recently came across the module "Rich". Honestly I don't know how I made it this far without the module. Not only is it really cool for making your output look a lot better with colored formatting but the features like "inspect" really help you dive into Python objects and help the Learning Process.
🌐
Rich
rich.readthedocs.io β€Ί en β€Ί stable β€Ί tables.html
Tables β€” Rich 14.1.0 documentation
highlight Set to True to enable automatic highlighting of cell contents. You can set the border style by importing one of the preset Box objects and setting the box argument in the table constructor. Here’s an example that modifies the look of the Star Wars table: from rich import box table = Table(title="Star Wars Movies", box=box.MINIMAL_DOUBLE_HEAD)
Top answer
1 of 1
2

I encountered the same problem. I need to find the text spans in red color in some rich-text cells. After diving into the source code of openpyxl (v3.0.9), I found it do parse the rich-text tags but the formats are stripped by the reader as the content property of Text object is used in the read_string_table function.

So, I wrote a simple patch script to override the read_string_table function such that the raw Text object is returned when formatted text exists. The modified read_string_table function is as below.

def read_string_table(xml_source):
    """Read in all shared strings in the table.
    If a shared string has formatted snippets, the raw Text object is appended to the returned list.
    Otherwise, only the plain text content of the shared string is appended to the list.
    """
    strings = []
    STRING_TAG = '{%s}si' % SHEET_MAIN_NS
    for _, node in iterparse(xml_source):
        if node.tag == STRING_TAG:
            text_obj = Text.from_tree(node)
            if text_obj.formatted:
                text = text_obj  # return raw Text object
            else:  # original processing
                text = text_obj.content
                text = text.replace('x005F_', '')
            node.clear()
            strings.append(text)
    return strings

The full patch script is available here. You need to import it and call the patch_read_string_table function before importing any openpyxl modules directly. After applying this patch, the value of a Rich-text cell will be a Text object that contains all the style information you want.

Depending on your use case, this might not be the best solution, but it shows you where the formats are stripped and how you may get them back. I hope that a more elegant solution can be proposed and eventually merged into the official code in the future.

🌐
Pybites
pybit.es β€Ί articles β€Ί learning-rich-by-making-a-color-searcher-command-line-app
Learning Rich by making a color searcher command line app – Pybites
Initially the table showed the matching colors in a pretty random order: ... So when I showed this on Twitter the creator of Rich (Will McGugan) chimed in asking if I β€œcould convert the RGB to HSL and sort by the L component?”
🌐
freeCodeCamp
freecodecamp.org β€Ί news β€Ί use-the-rich-library-in-python
How to Use the Rich Library with Python
February 8, 2022 - Rich is a Python library for writing rich text (with color and style) to the terminal. It lets you display advanced content such as tables, markdown, and syntax-highlighted code.
🌐
Rich
rich.readthedocs.io β€Ί en β€Ί stable β€Ί appendix β€Ί colors.html
Standard Colors β€” Rich 14.1.0 documentation
╔════════════╀════════╀═══════════════════════╀═════════╀══════════════════╗ β•‘ Color β”‚ Number β”‚ Name β”‚ Hex β”‚ RGB β•‘ β•Ÿβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•’ β•‘ β”‚ 0 β”‚ "black" β”‚ β”‚ β•‘ β•‘ β”‚ 1 β”‚ "red" β”‚ β”‚ β•‘ β•‘ β”‚ 2 β”‚ "green" β”‚
🌐
Medium
medium.com β€Ί trabe β€Ί building-rich-console-interfaces-in-python-16338cc30eaa
Building Rich Console Interfaces in Python | by MartΓ­n Lamas | Trabe | Medium
September 28, 2020 - Once the table structure is defined, we can insert a data row by calling the add_row method. We must pass the data as arguments in the same order the columns were defined. Each cell can be styled individually.