Search code examples
pythonpandaspygsheets

Pygsheets: How to highlight cells in a specific column based on a condition


I have a pandas data frame with three columns, and I want to highlight the cells in a specific column that meet a certain condition using pygsheets. How can I do that?

A                 B          C 
some_text         65      some_text


def color_my_cell(var):
    for i in wks.range('B3:B30'):
        if var < 70:
           wks.cell( NOT SURE what to do here).color = (1.0,0,1.0,1.0)

df['B'] = df['B'].apply(color_my_cell)

So, for any cells in B < 70, highlight cells blue.


Solution

  • you cant apply formats in df directly. you can do this by coloring cells by acessing each cell and setting color. but i think in your case whats more appropriate is conditional formatting. something like shown below. below code might not be exatly what you require refer to here and here

    request = {"AddConditionalFormatRuleRequest": {
    "ranges":[GridRange(worksheet=wks, start='B3', end='B30').to_json()],
    "booleanRule": {
    "condition":{"type::'NUMBER_GREATER', 'values': 70},
    "format":{"backgroundColor":{"color": {"green": 0.8,},}}}},
    "index":0}
    
    ssheet.custom_request(request, "*")