基于列组条件的DataFrame样式设置:分组高亮不等值
Solution
To achieve the desired conditional formatting in your pandas DataFrame, we can use pandas.Styler with a custom function that applies highlighting based on your criteria. Here's a step-by-step implementation:
Step 1: Import pandas and create the DataFrame
import pandas as pd from pandas import DataFrame # Create the DataFrame as specified df = DataFrame({ 'A': ['Bob', 'Rob', 'Dob'], 'B': ['Bob', 'Rob', 'Dob'], 'C': ['Bob', 'Dob', 'Dob'], 'D': ['Ben', 'Ten', 'Zen'], 'E': ['Ben', 'Ten', 'Zu'] })
Step 2: Define the custom styling function
This function checks each row to apply targeted highlighting:
- For columns A, B, C: Highlights cells that differ from the most common value (mode) in the row (catching any cell that doesn’t match the majority of values in these three columns).
- For columns D, E: Highlights both cells if their values are not equal.
def highlight_differences(row): # Initialize empty list to store styles for each cell cell_styles = [''] * len(row) # Handle A/B/C columns: Highlight non-matching values abc_values = row[['A', 'B', 'C']] if abc_values.nunique() != 1: # Get the most frequent value in the row's A/B/C columns most_common = abc_values.mode()[0] # Apply light red background to cells that don't match the most common value for col_idx, col_name in enumerate(['A', 'B', 'C']): if row[col_name] != most_common: cell_styles[col_idx] = 'background-color: #ffcccc' # Handle D/E columns: Highlight if values are unequal if row['D'] != row['E']: # Get indices of D and E columns d_col_idx = row.index.get_loc('D') e_col_idx = row.index.get_loc('E') # Apply light green background to both cells cell_styles[d_col_idx] = 'background-color: #ccffcc' cell_styles[e_col_idx] = 'background-color: #ccffcc' return cell_styles
Step 3: Apply the styling to the DataFrame
# Apply the custom style function to each row styled_df = df.style.apply(highlight_differences, axis=1) # Display the styled DataFrame (works in Jupyter/IPython environments) styled_df
Expected Result
When you run this code, the styled DataFrame will have:
- Row 1: Column C (value 'Dob') with a light red background (since it differs from A and B's 'Rob').
- Row 2: Columns D ('Zen') and E ('Zu') with a light green background (since their values don’t match).
- All other cells remain unhighlighted as they meet the matching criteria.
You can tweak the background colors by changing the hex codes in the background-color properties (e.g., #ff9999 for darker red, #99ff99 for darker green).
内容的提问来源于stack exchange,提问作者Sharvari Gc
相关产品推荐
相关产品推荐

