'Using Pandas dataframe, how can I highlight cells whose length > 5 on certain columns and output a new column to describe the error?

Given the following dataframe:

|  Item Part No 1 |  Item Part No 2 | Random Header |
| --------------- | --------------- | ------------- |
|  abcde          |  abcdefgh       | abcdgef       |
|  abcdefg        |  abcdefgh       | abcdefgh      |

How can I achieve the above?

|  Item Part No 1 |  Item Part No 2 | Random Header |  Error Message |
| --------------- | --------------- | ------------- |  ------------- |
|  abcde          |  **abcdefgh**   | abcdgef       |  exceed length |
|  **abcdefg**    |  **abcdefgh**   | abcdefgh      |  exceed length |

What I have done thus far:

df_filtered = df_equipment.filter(regex=("Item Part No"))

def highlight_cells(val, color_if_true, color_if_false):
    color = color_if_true if len(val) > 5 else color_if_false
    return 'background-color: {}'.format(color)

df_coloured = df_filtered.style.applymap(highlight_cells, color_if_true='yellow', color_if_false='#C6E2E9')

This does not work so far and how can I grab its index and output a column with the error message?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source