Highlight cells in a column in google spreadsheet when the value above a threshold with python

2024/10/6 9:03:28

Here is a simplified example of my codes and the screenshot of the results I want to get in google spreadsheet. I hope to either save the dataframe style to google spreadsheet as applying table style to excel using python. Or use the gspread-formatting to high-light the cell background when the value above the threshold.

Could anyone give me an example how to do this? Thank You!

cars = {'Brand': ['Honda Civic','Ferrari','Toyota Corolla','Ford Focus','Audi A4','TESLA','Ford Fusion','BENZ'],'Price': [22000,625000,25000,27000,35000,55000,28000,51000]}
df_car = pd.DataFrame(cars, columns = ['Brand', 'Price'])def _color_if_above_budget(s):return ['background-color: red' if val >50000 else '' for val in s]
s=df_car.style.apply(_color_if_above_budget, subset=['Price'])
ws=**worksheetgd.set_with_dataframe(worksheet=ws,dataframe=df_car,include_index=False,include_column_header=True,resize=True)

enter image description here

Answer

Use gspread_dataframe to set data to sheets and gspread_formatting to format the content of sheets with condition.

Try this code below:

import gspread
import pandas as pd
from gspread_dataframe import set_with_dataframe
from gspread_formatting import *gc = gspread.service_account()
sh = gc.open("example").sheet1
cars = {'Brand': ['Honda Civic','Ferrari','Toyota Corolla','Ford Focus','Audi A4','TESLA','Ford Fusion','BENZ'],'Price': [22000,625000,25000,27000,35000,55000,28000,51000]}
df_car = pd.DataFrame(cars, columns = ['Brand', 'Price'])
set_with_dataframe(sh, df_car)rule = ConditionalFormatRule(ranges=[GridRange.from_a1_range('B2:B', sh)],booleanRule=BooleanRule(condition=BooleanCondition('NUMBER_GREATER', ['50000']),format=CellFormat(textFormat=textFormat(bold=True), backgroundColor=Color(1,0,0)))
)
rules = get_conditional_format_rules(sh)
rules.append(rule)
rules.save()

Output:

example image

References:

gspread-formatting (Conditional Formatting)

gspread-dataframe

https://en.xdnf.cn/q/120188.html

Related Q&A

cannot concatenate str and file objects : Python error

I have Following piece of code: for src_filename, src_code in src_dict.iteritems(): try: set.dependencies = subprocess.check_output(unifdef -s /home/c/maindir/folder/ +src_filename, shell=True) except…

Run python script from html button submit

i have a code input data to txt file :<form action="proses.php" method="post">Nomor Polisi : <br><input type="text" name="nopol"><br><…

Reading log files in python

I have a log file (it is named data.log) containing data that I would like to read and manipulate. The file is structured as follows:#Comment line 1 #Comment line 2 1.00000000,3.02502604,343260.6865…

Return more than one value in python function [duplicate]

This question already has answers here:How can I use `return` to get back multiple values from a loop? Can I put them in a list?(2 answers)Closed 1 year ago.I was trying to use *args with a for loop …

Python: Making a class to use complex numbers

I am currently trying to write a program that deals with complex numbers. I have to use classes and methods. I am trying to be able to add, subtract, multiply etc., complex numbers, as well as compare …

Return does not return anything in Spyder. It works fine with other IDE

I just moved to spyder for Python and the return function doesnt seem to work: def test():return 2 test()The IPython console is empty. If I use print instead of return it works fine. Any idea? I use p…

Error in goto module [Python]

Ok, let me start by saying I know that it is bad that I am using the goto module and I shouldnt be and blah blah blah. However, for this specific purpose I need it. Let me also say that I am new to Pyt…

How to scrape all product review from lazada in python

i currently working on web scraping of data from the lazada site using selenium in python: https://www.lazada.sg/products/loreal-paris-uv-perfect-even-complexion-sunscreen-spf50pa-30ml-i214861100-s325…

How to compare 2 successive row values in a resultset object using python

I have a table issue_logs:id | issue_id | from_status | to_status | up_date | remarks ----+----------+-------------+-----------+----------------------------------+----------…

Getting all possible combination for [1,0] with length 3 [0,0,0] to [1,1,1]

from itertools import combinationsdef n_length_combo(arr, n):# using set to deal# with duplicates return list(combinations(arr, n))# Driver Function if __name__ == "__main__":arr = 01n = 3pri…